OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

2019-09-02 17:21:52 浏览数 (2)

1.HttpURLConnection

代码语言:javascript复制
 1 public class HttpURLConnectionGetAndPost {
 2     private String urlAddress = "xxxx";
 3 
 4     public void doGet(String method, String s) throws IOException {
 5         String getUrl = urlAddress   method   "?sex="   s;
 6 
 7         URL url = new URL(getUrl);
 8         HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 9         httpURLConnection.connect();
10         if (httpURLConnection.getResponseCode() == 200) {
11             StringBuffer sb = new StringBuffer();
12             InputStream in = httpURLConnection.getInputStream();
13             BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
14             String readLine = "";
15 
16             while ((readLine = bufferReader.readLine()) != null) {
17                 sb.append(readLine);
18             }
19             in.close();
20             bufferReader.close();
21             httpURLConnection.disconnect();
22 
23             Log.d("test", sb.toString());
24 
25         } else {
26             Log.d("test", "get failed");
27         }
28 
29     }
30 
31     public void doPost(String method, String s) throws IOException {
32 
33         URL url = new URL(urlAddress   method);
34         HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
35         httpURLConnection.setDoInput(true);
36         httpURLConnection.setDoOutput(true);
37         httpURLConnection.setReadTimeout(10000);
38         httpURLConnection.setConnectTimeout(10000);
39         httpURLConnection.setRequestMethod("POST");
40         httpURLConnection.setUseCaches(false);
41         httpURLConnection.setRequestProperty("content-type", "");
42         httpURLConnection.setRequestProperty("content-type", "");
43         httpURLConnection.connect();
44         DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
45 
46         String content = "sex="   s;
47 
48         dataOutputStream.writeBytes(content);
49         dataOutputStream.flush();
50         dataOutputStream.close();
51 
52         if (httpURLConnection.getResponseCode() == 200) {
53             InputStream inputStream = httpURLConnection.getInputStream();
54             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
55             String readLine = "";
56             StringBuffer sb = new StringBuffer();
57             while ((readLine = bufferedReader.readLine()) != null) {
58                 sb.append(readLine);
59             }
60             bufferedReader.close();
61             inputStream.close();
62             httpURLConnection.disconnect();
63             Log.d("test", sb.toString());
64         } else {
65             Log.d("test", "post failed");
66         }
67     }
68 }

2.HttpClient

代码语言:javascript复制
 1 public class HttpClientGetAndPost {
 2     private String urlAddress = "xxxx";
 3     private void doGet(String method, String s){
 4         
 5         String getUrl = urlAddress  method    "?sex= "  s;
 6         HttpGet httpGet = new HttpGet(getUrl);
 7         try {
 8             HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
 9             if(httpResponse.getStatusLine().getStatusCode() ==200){
10                 String result  = EntityUtils.toString(httpResponse.getEntity());
11                 Log.d("test","result=" result);
12             }else{
13                 
14                 Log.d("test","get failed");
15             }
16         } catch (ClientProtocolException e) {
17             // TODO Auto-generated catch block
18             e.printStackTrace();
19         } catch (IOException e) {
20             // TODO Auto-generated catch block
21             e.printStackTrace();
22         }
23          
24         
25       ///  HttpPost 
26     }
27     
28     
29     private void doPost(String method, String s) throws ClientProtocolException, IOException{
30         HttpPost httpPost = new HttpPost(urlAddress method);
31         List<NameValuePair> parms = new ArrayList<NameValuePair>();
32         parms.add(new BasicNameValuePair("sex",s)  );
33         httpPost.setEntity(new UrlEncodedFormEntity(parms,HTTP.UTF_8));
34         HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
35         if(httpResponse.getStatusLine().getStatusCode() ==200){
36             String result  = EntityUtils.toString(httpResponse.getEntity());
37             Log.d("test","result=" result);
38         }else{
39             
40             Log.d("test","post failed");
41         }
42     }
43 }

3. OKHttp3

代码语言:javascript复制
 1 public class OkHttpGetAndPost {
 2 
 3 private String urlAddress = "xxxx";
 4 private OkHttpClient okHttpClient = new OkHttpClient();
 5 
 6 private void doGet(String method, String s) throws IOException {
 7 String url = urlAddress   method   "?sex="   s;
 8 Request request = new Request.Builder().url(url).get().build();
 9 Response respone = okHttpClient.newCall(request).execute();
10 if (respone.isSuccessful()) {
11 Log.d("test", respone.body().string());
12 } else {
13 Log.d("test", "get failed");
14 }
15 }
16 
17 private void doPost(String method, String s) {
18 FormBody formBody = new FormBody.Builder().add("sex", s).build();
19 RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{"sex","" s ""}");
20 Request request = new Request.Builder().url(urlAddress   method).post(body).build();
21 okHttpClient.newCall(request).enqueue(new Callback() {
22 @Override
23 public void onResponse(Call arg0, Response arg1) throws IOException {
24 Log.d("test", arg1.body().string());
25 }
26 @Override
27 public void onFailure(Call arg0, IOException arg1) {
28 Log.d("test", "post failed");
29 }
30 });
31 }
32 }

由以上demo可以看出,OKHttp使用最简单方便,代码书写量少,而且网络请求高效。

如果喜欢作者的文章,请关注"写代码的猿"订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载.

0 人点赞