Android常用库源码解析(2)

常用网络库使用方法

public interface netApi { @GET("repos/{owner}/{repo}/contributors") Call<ResponseBody> contributorsBySimpleGetCall(@Path("owner") String owner, @Path("repo") String repo); } public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); volleyStringRequest(); volleyJsonRequest(); retrofitHttpRequest(); try { okhttpAsyGet(); OkHttpSyncGet(); } catch (Exception e) { e.printStackTrace(); } } //volley第一步 RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this); private void volleyStringRequest() { //volley第二步 StringRequest stringRequest = new StringRequest("http://www.baidu.com", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("TAG", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); } }); //volley第三步 mQueue.add(stringRequest); } private void volleyJsonRequest() { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://www.sina.com/sports/101010100.html", null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("TAG", response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); } }); mQueue.add(jsonObjectRequest); } //okhttp第一步 private final OkHttpClient client = new OkHttpClient(); public void okhttpAsyGet() throws Exception { //okhttp第二步 Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); //okhttp第三步 okhttp3.Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } public void OkHttpSyncGet() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, okhttp3.Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string());//只能获取一次,可以用string保存 } }); } public void retrofitHttpRequest() { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); netApi repo = retrofit.create(netApi.class); retrofit2.Call<ResponseBody> call = repo.contributorsBySimpleGetCall("userName", "path"); call.enqueue(new retrofit2.Callback<ResponseBody>() { @Override public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { //response } @Override public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) { } }); } } String post(String url, String json) throws IOException { RequestBody formBody = new FormEncodingBuilder() .add("platform", "Android") .add("name", "bug") .add("subject", "XXXXXXXXXXXXXXX") .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } }

HttpURLConnection和HttpClient。这两种方式都支持HTTPS协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。

在Android 2.2版本之前,HttpClient是最好的选择。因为HttpURLConnection有一些bug。比如说对一个可读的InputStream调用close()方法时,就有可能会导致连接池失效了。那么我们通常的解决办法就是直接禁用掉连接池的功能。

在Android 2.3版本及以后,HttpClientHttpURLConnection则是最佳的选择,HttpURLConnection的API提供的比较简单,可以更加容易地去使用和扩展它。而且速度快、节省电量。

OkHttp 处理了很多网络问题:自动重连、会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/10fd66b75d0720694b7b47ab87a0b04b.html