Java.net.SocketException在使用OkHttp进行GET请求时发生。

huangapple go评论96阅读模式
英文:

Java.net.SocketException occur when use OkHttp get request

问题

以下是翻译后的内容:

我正在尝试测试这个应用程序它运行时出现了 Socket 异常不进行 HTTP 请求也不显示我想要的数据

这只是应用程序中的一个活动

public class MainActivity extends AppCompatActivity {
    private static final String url =
            "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&orderby=time&minmag=6&limit=10";

    private EarthAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置适配器
        ListView listView = findViewById(R.id.list);

        mAdapter = new EarthAdapter(this, new ArrayList<Earthquake>());
        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Earthquake currentEarthquake = mAdapter.getItem(position);
                Uri earthquakeUri = Uri.parse(currentEarthquake.getmUrl());
                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);
                startActivity(websiteIntent);
            }
        });

        Task task = new Task();
        task.execute(url);
    }

    // ... 以下代码略
}

这是 AndroidManifest 文件,我添加了所有可能导致异常的权限。
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.earthquakereport">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是 logcat 和异常详细信息。
Logcat

E/do in background: ::::::::::
java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.getImpl(Socket.java:552)
    at java.net.Socket.setSoTimeout(Socket.java:1180)
    at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:293)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:207)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
    at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
    at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
    at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
    at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
    at com.example.earthquakereport.MainActivity$Task.run(MainActivity.java:106)
    at com.example.earthquakereport.MainActivity$Task.doInBackground(MainActivity.java:73)
    at com.example.earthquakereport.MainActivity$Task.doInBackground(MainActivity.java:65)
    at android.os.AsyncTask$3.call(AsyncTask.java:378)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
    Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
        ... 28 more
    Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
        ... 28 more
    // 更多相似的抑制异常...
英文:

I am trying to test the app it runs put make a Socket Exception and doesn't make the HTTP request and doesn't display the data I want.

This is only one activity on the app:

public class MainActivity extends AppCompatActivity {
    private static final String url =
            &quot;https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&amp;orderby=time&amp;minmag=6&amp;limit=10&quot;;

    private EarthAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting Adapter
        ListView listView = findViewById(R.id.list);

        mAdapter = new EarthAdapter(this, new ArrayList&lt;Earthquake&gt;());
        listView.setAdapter(mAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
                Earthquake currentEarthquake = mAdapter.getItem(position);
                Uri earthquakeUri = Uri.parse(currentEarthquake.getmUrl());
                Intent websiteIntent = new Intent(Intent.ACTION_VIEW, earthquakeUri);
                startActivity(websiteIntent);
            }
        });

        Task task = new Task();
        task.execute(url);

    }

    //////////////////////////
    private class Task extends AsyncTask&lt;String, Void, List&lt;Earthquake&gt;&gt; {

        @Override
        protected List&lt;Earthquake&gt; doInBackground(String... strings) {
            List&lt;Earthquake&gt; earthquakes = new ArrayList&lt;&gt;();
            if (strings.length &gt; 0 &amp;&amp; strings[0] != null) {
                try {
                    earthquakes = dataQuery(run(strings[0]));
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(&quot;do in background&quot;, &quot;::::::::::&quot;, e);
                }
                return earthquakes;
            }

            return earthquakes;
        }

        @Override
        protected void onPostExecute(List&lt;Earthquake&gt; earthquakes) {
            super.onPostExecute(earthquakes);
            // Clear the adapter of previous earthquake data
            mAdapter.clear();

            // If there is a valid list of {@link Earthquake}s, then add them to the adapter&#39;s
            // data set. This will trigger the ListView to update.
            if (earthquakes != null &amp;&amp; !earthquakes.isEmpty()) {
                mAdapter.addAll(earthquakes);
            }

        }

        String run(String url) throws IOException {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                return response.body().string();
            }
        }

        public List&lt;Earthquake&gt; dataQuery(String s) {

            List&lt;Earthquake&gt; earthquakes = new ArrayList&lt;&gt;();

            try {
                JSONObject root = new JSONObject(s);
                JSONArray features = root.getJSONArray(&quot;features&quot;);

                for (int i = 0; i &lt; features.length(); i++) {
                    JSONObject currentItem = features.getJSONObject(i);
                    JSONObject properties = currentItem.getJSONObject(&quot;properties&quot;);

                    double mag = properties.getDouble(&quot;mag&quot;);

                    String place = properties.optString(&quot;place&quot;);
                    String place1, place2;
                    if (place.contains(&quot; of &quot;)) {
                        int x = place.indexOf(&quot;of&quot;);
                        place1 = place.substring(0, x + 2);
                        place2 = place.substring(x + 3);
                    } else {
                        place1 = &quot;Near the&quot;;
                        place2 = place;
                    }
                    long timeLong = properties.getLong(&quot;time&quot;);
                    Date dateObject = new Date(timeLong);
                    SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
                    SimpleDateFormat timeFormat = new SimpleDateFormat(&quot;HH:MM a&quot;);
                    String date = dateFormat.format(dateObject);
                    String time = timeFormat.format(dateObject);


                    String url = properties.getString(&quot;url&quot;);


                    earthquakes.add(new Earthquake(mag, place1, place2, date, time, url));
                }
            } catch (JSONException e) {

            }
            return earthquakes;
        }
    }
}

This is the AndroidManifest file and I am adding all permissions I found that may be case the exception.
AndroidManifest.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.example.earthquakereport&quot;&gt;
    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.CHANGE_WIFI_STATE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.CHANGE_NETWORK_STATE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot; /&gt;

    &lt;application
        android:allowBackup=&quot;true&quot;
        android:icon=&quot;@mipmap/ic_launcher&quot;
        android:label=&quot;@string/app_name&quot;
        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
        android:supportsRtl=&quot;true&quot;
        android:theme=&quot;@style/AppTheme&quot;&gt;
        &lt;activity android:name=&quot;.MainActivity&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
    &lt;/application&gt;

&lt;/manifest&gt;

This is the logcat and exception details.
Logcat

E/do&#160;in&#160;background: ::::::::::
java.net.SocketException: socket failed: EPERM (Operation not permitted)
    at java.net.Socket.createImpl(Socket.java:492)
    at java.net.Socket.getImpl(Socket.java:552)
    at java.net.Socket.setSoTimeout(Socket.java:1180)
    at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:293)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:207)
    at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
    at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
    at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
    at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
    at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
    at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
    at com.example.earthquakereport.MainActivity$Task.run(MainActivity.java:106)
    at com.example.earthquakereport.MainActivity$Task.doInBackground(MainActivity.java:73)
    at com.example.earthquakereport.MainActivity$Task.doInBackground(MainActivity.java:65)
    at android.os.AsyncTask$3.call(AsyncTask.java:378)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more
	Suppressed: java.net.SocketException: socket failed: EPERM (Operation not permitted)
		... 28 more

答案1

得分: 0

已解决

只需从模拟器中卸载该应用,然后重新运行即可。

英文:

Solved

just uninstall the app from the emulator and run it again.

huangapple
  • 本文由 发表于 2020年7月25日 23:51:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63090373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定