前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

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

作者头像
yuanyuan
发布2019-09-02 17:21:52
4780
发布2019-09-02 17:21:52
举报
文章被收录于专栏:小满小满

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使用最简单方便,代码书写量少,而且网络请求高效。

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-04-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档