OKHttp源码学习

Stella981
• 阅读 547

1.HttpURLConnection

 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

 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

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

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

OKHttp源码学习

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
3年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这