OkHttp Library - NetworkOnMainThreadException on simple post

后端 未结 3 1755
北海茫月
北海茫月 2020-11-28 06:52

I want to use OkHttp library for networking in Android. I started with the simple post example as written in their website:

public static final MediaType JSO         


        
相关标签:
3条回答
  • 2020-11-28 07:37

    According to the OkHttp docs: It supports both synchronous blocking calls and async calls with callbacks. Your example is on main thread and Android since version 3.0 throws that exception if you try to do network calls on main thread

    Better option is to use it together with retrofit and Gson: http://square.github.io/retrofit/ https://code.google.com/p/google-gson/

    Here are the examples: http://engineering.meetme.com/2014/03/best-practices-for-consuming-apis-on-android/ http://heriman.net/?p=5

    0 讨论(0)
  • 2020-11-28 07:39

    You should use OkHttp's async method.

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    OkHttpClient client = new OkHttpClient();
    
    Call post(String url, String json, Callback callback) {
      RequestBody body = RequestBody.create(JSON, json);
      Request request = new Request.Builder()
          .url(url)
          .post(body)
          .build();
      Call call = client.newCall(request);
      call.enqueue(callback);
      return call;
    }
    

    And then your response would be handled in the callback (OkHttp 2.x):

    post("http://www.roundsapp.com/post", json, new Callback() {
      @Override
      public void onFailure(Request request, Throwable throwable) {
         // Something went wrong
      }
    
      @Override public void onResponse(Response response) throws IOException {
        if (response.isSuccessful()) {
           String responseStr = response.body().string();
           // Do what you want to do with the response.
        } else {
           // Request not successful
        }
      }
    });
    

    Or OkHttp 3.x/4.x:

    post("http://www.roundsapp.com/post", "", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Something went wrong
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();
                    // Do what you want to do with the response.
                } else {
                    // Request not successful
                }
            }
        });
    

    Take a look at their recipes for more examples: http://square.github.io/okhttp/recipes/

    0 讨论(0)
  • 2020-11-28 07:49

    If you follows these steps to implement OKHTTP, then definitely you'll call multiple API on multiple screen by applying only two lines of code

    UpdateListener updateListener = new UpdateListener(HitAPIActivity.this, baseHTTPRequest);
    updateListener.getJsonData();
    

    Step 1:

    baseHTTPRequest = new BaseHTTPRequest();
        //    baseHTTPRequest.setURL("https://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demohttps://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");
    baseHTTPRequest.setURL("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
            baseHTTPRequest.setRequestCode(reqType);
            baseHTTPRequest.setCachedRequired(true);
    
            UpdateListener updateListener = new UpdateListener(HitAPIActivity.this, baseHTTPRequest);
            updateListener.executeRequest();
    

    Step 2 : Create a request class

    /** * Created by Deepak Sharma on 4/7/16. * This is a HTTP request class which has the basic parameters. * If you wants to add some more parameters, please make a subclass of that class * and add with your subclass. Don't modify this class. */

     public class BaseHTTPRequest<T> {
    
        private Context context;
        private String URL;
        private int requestCode;
        private List<T> listParameters;
        private String header;
        private boolean isCachedRequired;
    
        public Context getContext() {
            return context;
        }
        public void setContext(Context context) {
            this.context = context;
        }
        public void setURL(String URL) {
            this.URL = URL;
        }
        public String getURL() {
            return URL;
        }
    
        public int getRequestCode() {
            return requestCode;
        }
    
        public void setRequestCode(int requestCode) {
            this.requestCode = requestCode;
        }
    
        public List<T> getListParameters() {
            return listParameters;
        }
    
        public void setListParameters(List<T> listParameters) {
            this.listParameters = listParameters;
        }
    
        public String getHeader() {
            return header;
        }
    
        public void setHeader(String header) {
            this.header = header;
        }
    
        public boolean isCachedRequired() {
            return isCachedRequired;
        }
        public void setCachedRequired(boolean cachedRequired) {
            isCachedRequired = cachedRequired;
        }
    }
    

    step 4 : Create a listener class

    import android.util.Log; import com.google.gson.Gson; import java.io.IOException; import dxswifi_direct.com.wifidirectcommunication.base.model.request.BaseHTTPRequest; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Callback; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;

    /** * Created by Deepak Sharma on 4/7/16. * @email : dpsharma.sharma1@gmail.com * This is a Simple java class which will help you for HTTP request/response and it will * throw the response to your correspondance activity. */

    public class UpdateListener {
    
        private OnUpdateViewListener onUpdateViewListener;
    
        OkHttpClient okHttpClient = new OkHttpClient();
        BaseHTTPRequest mRequestModel;
        private String mURL = null;
        private Request mRequest = null;
    
        public interface OnUpdateViewListener {
            void updateView(String responseString, boolean isSuccess,int reqType);
        }
    
        public UpdateListener(OnUpdateViewListener onUpdateView, final BaseHTTPRequest requestModel) {
            this.mRequestModel = requestModel;
            this.onUpdateViewListener = onUpdateView;
    
            if (requestModel.isCachedRequired())
            {
                /*File httpCacheDirectory = new File(requestModel.getContext().getCacheDir(), "responses");
                Cache cache = null;
                cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
                if (cache != null) {
                    okHttpClient.setCache(cache);
                }*/
            }
    
            /*mURL = null;
            if (requestModel.getListParameters()!=null && requestModel.getListParameters().size()>0)
            {
                HttpUrl.Builder urlBuilder = HttpUrl.parse(requestModel.getURL()).newBuilder();
                List<RequestParameter> requestParameters = requestModel.getListParameters();
                for (int i=0; i<requestParameters.size();i++)
                {
                    urlBuilder.addQueryParameter(requestParameters.get(i).getKey(),requestParameters.get(i).getValue());
                }
                mURL = urlBuilder.build().toString();
            }
            else
            {
                mURL = requestModel.getURL();
            }*/
    
                mURL = requestModel.getURL();
            if (mRequestModel.getListParameters()!=null && mRequestModel.getListParameters().size()>1)
            {
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                mRequest = new Request.Builder()
                        .url(mURL)
                        .post(RequestBody.create(JSON, new Gson().toJson(BaseHTTPRequest.class)))
                        .build();
            }
            else
            {
                mRequest = new Request.Builder()
                        .url(mURL)
                        .build();
            }
    
        }
    
        public void executeRequest()
        {
            Call call = okHttpClient.newCall(mRequest);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    onUpdateViewListener.updateView(NetworkException.getErrorMessage(e), false, mRequestModel.getRequestCode());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        // You can also throw your own custom exception
                        throw new IOException("Unexpected code " + response);
                    } else {
                        Log.i("Response:",response.toString());
                        Log.i("Response body:",response.body().toString());
                        Log.i("Response message:",response.message());
                        onUpdateViewListener.updateView(response.body().string(),true, mRequestModel.getRequestCode());
                    }
                    // do something wih the result
                }
            });
        }
    }
    

    step 5 : From the activity you requesting, implement listener

    public class HitAPIActivity extends AppCompatActivity implements View.OnClickListener, UpdateListener.OnUpdateViewListener{
    
    @Override
        public void updateView(final String responseString, boolean isSuccess, int reqType) {
    
    if (isSuccess)
            {
    
    if (!responseString.contains("failure")
                        && !responseString.contains("Error")) {
                    // Handle request on the basis of Request Type.
                    switch (reqType) {
                        case ApiConstants.GET_CONTACTS:
    
    break;
    
    default:
    break;
    
    }
    
    }
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题