web-dev-qa-db-fra.com

java.net.SocketTimeoutException dans okhttp

Ici, il faut tellement de temps pour obtenir des données de json. Une fois supprimé et à nouveau installé, il obtiendra json en 1 min et lorsque je clique à nouveau sur le bouton pour json cela prend tellement de temps et les données ne parviennent toujours pas dans listview

Voici mon code d'exception

E/JSONDemo: IOExceptiojava.net.SocketTimeoutException
  at Java.net.PlainSocketImpl.read(PlainSocketImpl.Java:493)
  at Java.net.PlainSocketImpl.-wrap0(PlainSocketImpl.Java)
  at Java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.Java:242)
  at okio.Okio$2.read(Okio.Java:140)
  at okio.AsyncTimeout$2.read(AsyncTimeout.Java:238)
  at okio.RealBufferedSource.indexOf(RealBufferedSource.Java:325)
  at okio.RealBufferedSource.indexOf(RealBufferedSource.Java:314)
  at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.Java:210)
  at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.Java:184)
  at okhttp3.internal.http.Http1xStream.readResponseHeaders(Http1xStream.Java:125)
  at okhttp3.internal.http.HttpEngine.readNetworkResponse(HttpEngine.Java:775)
  at okhttp3.internal.http.HttpEngine.access$200(HttpEngine.Java:86)
  at okhttp3.internal.http.HttpEngine$NetworkInterceptorChain.proceed(HttpEngine.Java:760)
  at okhttp3.internal.http.HttpEngine.readResponse(HttpEngine.Java:613)
  at okhttp3.RealCall.getResponse(RealCall.Java:244)
  at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.Java:201)
  at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.Java:163)
  at okhttp3.RealCall.access$100(RealCall.Java:30)
  at okhttp3.RealCall$AsyncCall.execute(RealCall.Java:127)
  at okhttp3.internal.NamedRunnable.run(NamedRunnable.Java:32)
  at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1113)
  at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:588)
  at Java.lang.Thread.run(Thread.Java:818)

voici un code json dans Java:

progress = ProgressDialog.show(MainActivity.this, "dialog title", "dialog message", true);
Toast.makeText(MainActivity.this, "ok", Toast.LENGTH_LONG).show();

    if (isNetworkAvailable()) {

        String url = "ConstantValue.URL";
        RequestBody formBody = new FormBody.Builder()
                .add(employeeId, value)
                .build();

        try {
            post(url, formBody, new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("JSONDemo", "IOException", e);
                }

                @Override
                public void onResponse(final Call call, final Response response) throws IOException {
                    String JSON = response.body().string();
                     Log.e("res", " " + JSON);
                     try {
                         JSONObject jsonObj = new JSONObject(JSON);
                         JSONArray resultarr = jsonObj.getJSONArray("result");
                         final JSONArray resultarr1 = jsonObj.getJSONArray("result1");

                         if (resultarr1.length() == 0) {
                             showAlertDialog("API", "Data Unavailable");
                         } else {

                             for (int i = 0; i < resultarr1.length(); i++) {

                                 Employee emp = new Employee();
                                 JSONObject result1obj = resultarr1.getJSONObject(i);
                                 String result1Id = result1obj.getString("ID");
                                 String result1Name = result1obj.getString("NAME");
                                 String result1Value = result1obj.getString("VALUE");
                                 Log.e("result", " " + result1Name);
                                 Log.e("result", " " + result1Value);
                                 Log.e("result", " " + result1Id);
                                 emp.setValue(result1Value);
                                 emp.setName(result1Name);
                                 emp.setId(result1Id);

                                 arr.add(emp);

                             }
                         }

                         runOnUiThread(new Runnable() {
                             @Override
                             public void run() {

                                 // you can access all the UI componenet
                                 if (progress.isShowing()) 
                                     progress.dismiss();
                                 cu.notifyDataSetChanged();
                             }
                         });
                     } catch (Exception e) {
                         Log.e("JSONDemo", "onResponse", e);
                         showAlertDialog("API","Something went wrong");
                     }

                 }
             });

         } catch (Exception e) {
             Log.e("JSONDemo", "Post Exception", e);
         }

     } else {
         Toast.makeText(MainActivity.this, "Internet not available", Toast.LENGTH_LONG).show();
     }
}

Autres codes:

private final OkHttpClient client = new OkHttpClient();


Call post(String url, RequestBody formBody, Callback callback) throws IOException {

    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();

    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
18
Abhi

IOExceptiojava.net.SocketTimeoutException se produit à la condition suivante.

  1. Le serveur est lent et le délai d'expiration par défaut est inférieur. il suffit donc de mettre une valeur de timeout selon vous.
  2. Le serveur fonctionne correctement mais la valeur de délai d'attente est pour moins de temps. modifiez donc la valeur du délai d'expiration. comme l'extrait de code ci-dessous.

Client OkHttpClient = new OkHttpClient ();

client.setConnectTimeout(30, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);

Si vous utilisez okhttp3, vous devez le faire à l'aide du générateur.

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.SECONDS); 
builder.readTimeout(30, TimeUnit.SECONDS); 
builder.writeTimeout(30, TimeUnit.SECONDS); 
client = builder.build();
37
DroidNinja