专栏首页小满OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

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

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

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • android双待手机获取每一张SIM卡的imei

    /** * create a TelephonyInfo.java class */ import java.lang.reflect.Method;

    yuanyuan
  • android学习笔记--Scanner

    private static List<String> getxxxx(Context ctx) { try {

    yuanyuan
  • Javapoet源码解析

    github:https://github.com/square/javapoet

    yuanyuan
  • spring系列之自定义扩展PropertyPlaceHolderConfigurer

    一、PropertyPlaceHolderConfigurer介绍 主要用于将一些配置信息移出xml文件,移到至properties文件 二、拓展使用 1、将...

    lyb-geek
  • 【Java】07 常见 API

       Object 类是所有类的父类,若一个类没有指定继承的类则继承Object。任一类都直接或间接继承于Object。

    Demo_Null
  • 反射利器——jOOR

    反射提供了运行时修改对象的能力,但Java提供的Refelec包实在是太复杂了,首先得到Class、再根据Class去找到Field或Method,再进行调用,...

    用户1108631
  • zookeeper 根据服务名称初始化 服务地址列表

    爱明依
  • 项目工具类

    一、前言     在工作中,难免遇到各种各样的问题,每个人似乎都有一套自己的解决方案。而我,又不想每次解决完问题就把东西扔了,捡了芝麻,丢了西瓜,什么时候才能进...

    JMCui
  • 找出两个文件中相同的单词(java实现)

    第二种比较单词的方法:将string【】数组转换成集合,通过集合的retainAll()方法 两个集合取交集

    崔笑颜
  • 微信扫码支付

    一,需要申请公司的微信公众号,以及商户号。然后在商户号中关联微信公众APPID。在商户平台添加扫码支付功能。

    故久

扫码关注云+社区

领取腾讯云代金券