http request network request to read data from the network

read network data

URL httpUrl = new URL(jsonUrl);//Create url http address

HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//Open http link

InputStream in = conn.getInputStream();//Get the input stream//This sentence blocks the single-threaded thread.

 

Reading network data in android must be in a child thread

httpRead(url,callback){

   Handler handler=new Handler();//Use the main thread

    new Thread(){

          public void run(){

                  URL httpUrl = new URL(jsonUrl);//Create url http address

                  HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//Open http link

                  InputStream in = conn.getInputStream();//Get the input stream//This sentence blocks the single-threaded thread.

----------------------------------------------------------------------------------

                  When the network returns success:

                  String str=read data from in;

                  //The onSucces that executes the callback in the current child thread

                  callback.onSucces(str);

 

                 //Use the handler to go to the main thread to execute onSucces

                  handler.post(new Runnable(){

                         callback.onSucces(str);

                  });

-----------------------------------------------------------------------------------------------------------

                  When the network returns a failure:

                  //execute callback's onError in the current child thread

                  callback.onError();

 

                  /Use handler to go to the main thread to execute onError

                   handler.post(new Runnable(){

                         callback.onSucces(str);/

                  });

          }

    }

}

 

The third-party library has encapsulated the above logic of opening up the thread and reverting to the main thread. Just pass the url and callback. Note that the callback has not fallen to the thread.

For example: the third-party network library android-async-http:

asyncHttpClient=new AsyncHttpClient();//The entire project only needs one.

asyncHttpClient.get(jsonUrl, new TextHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                      //主线程执行,responseString是网络返回的结果

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                      //主线程执行网络出错
            }

}

 

例如:第三方网络库Volley:

RequestQueue requestQueue= Volley.newRequestQueue(context);

StringRequest request = new StringRequest(Request.Method.GET,

      url,

      new Response.Listener<String>() {

            public void onResponse(String s) {

                    //主线程执行,s是网络返回的结果

            }

        },

        new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError volleyError) {

                    //主线程执行网络出错

            }

        });

requestQueue.add(request);

//request可以设置超时时间

request.setRetryPolicy(new DefaultRetryPolicy(

                60000, //timeout时间

                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,//重连次数

                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

注意5.0以上需要在主模块build.gradle加

android {

    useLibrary 'org.apache.http.legacy'//必须在第一行

 

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326888007&siteId=291194637