OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比
1.HttpURLConnection
public class HttpURLConnectionGetAndPost {
private String urlAddress = "xxxx";
public void doGet(String method, String s) throws IOException {
String getUrl = urlAddress + method + "?sex=" + s;
URL url = new URL(getUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
StringBuffer sb = new StringBuffer();
InputStream in = httpURLConnection.getInputStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
String readLine = "";
while ((readLine = bufferReader.readLine()) != null) {
sb.append(readLine);
}
in.close();
bufferReader.close();
httpURLConnection.disconnect();
Log.d("test", sb.toString());
} else {
Log.d("test", "get failed");
}
}
public void doPost(String method, String s) throws IOException {
URL url = new URL(urlAddress + method);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("content-type", "");
httpURLConnection.setRequestProperty("content-type", "");
httpURLConnection.connect();
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
String content = "sex=" + s;
dataOutputStream.writeBytes(content);
dataOutputStream.flush();
dataOutputStream.close();
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = "";
StringBuffer sb = new StringBuffer();
while ((readLine = bufferedReader.readLine()) != null) {
sb.append(readLine);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d("test", sb.toString());
} else {
Log.d("test", "post failed");
}
}
}
2.HttpClient
public class HttpClientGetAndPost {
private String urlAddress = "xxxx";
private void doGet(String method, String s){
String getUrl = urlAddress+ method + "?sex= "+ s;
HttpGet httpGet = new HttpGet(getUrl);
try {
HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() ==200){
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d("test","result="+result);
}else{
Log.d("test","get failed");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/// HttpPost
}
private void doPost(String method, String s) throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(urlAddress+method);
List<NameValuePair> parms = new ArrayList<NameValuePair>();
parms.add(new BasicNameValuePair("sex",s) );
httpPost.setEntity(new UrlEncodedFormEntity(parms,HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
if(httpResponse.getStatusLine().getStatusCode() ==200){
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d("test","result="+result);
}else{
Log.d("test","post failed");
}
}
}
3. OKHttp3
public class OkHttpGetAndPost {
private String urlAddress = "xxxx";
private OkHttpClient okHttpClient = new OkHttpClient();
private void doGet(String method, String s) throws IOException {
String url = urlAddress + method + "?sex=" + s;
Request request = new Request.Builder().url(url).get().build();
Response respone = okHttpClient.newCall(request).execute();
if (respone.isSuccessful()) {
Log.d("test", respone.body().string());
} else {
Log.d("test", "get failed");
}
}
private void doPost(String method, String s) {
FormBody formBody = new FormBody.Builder().add("sex", s).build();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"sex\",\""+s+"\"}");
Request request = new Request.Builder().url(urlAddress + method).post(body).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
Log.d("test", arg1.body().string());
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.d("test", "post failed");
}
});
}
}
由以上demo可以看出,OKHttp使用最简单方便,代码书写量少,而且网络请求高效。
如果喜欢作者的文章,请关注"写代码的猿"订阅号以便第一时间获得最新内容。本文版权归作者所有,欢迎转载.

OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比的更多相关文章
- OKHttp源码学习同步请求和异步请求(二)
OKHttp get private void doGet(String method, String s) throws IOException { String url = urlAddress ...
- OKHttp源码解析
http://frodoking.github.io/2015/03/12/android-okhttp/ Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 A ...
- 【转载】okhttp源码解析
转自:http://www.open-open.com/lib/view/open1472216742720.html https://blog.piasy.com/2016/07/11/Unders ...
- Okhttp源码分析--基本使用流程分析
Okhttp源码分析--基本使用流程分析 一. 使用 同步请求 OkHttpClient okHttpClient=new OkHttpClient(); Request request=new Re ...
- 从设计模式角度看OkHttp源码
前言 说到源码,很多朋友都觉得复杂,难理解. 但是,如果是一个结构清晰且完全解耦的优质源码库呢? OkHttp就是这样一个存在,对于这个原生网络框架,想必大家也看过很多很多相关的源码解析了. 它的源码 ...
- OkHttp 源码分析
在工作中用到封装HTTP传输的OkHTTP,OkHttp是相对成熟的解决方案,同时也是开源项目.本文将从源码角度看下OkHttp是如何实现一些网络操作的. HTTP GET: OkHttpClient ...
- 深入理解OkHttp源码(一)——提交请求
本篇文章主要介绍OkHttp执行同步和异步请求的大体流程.主要流程如下图: 主要分析到getResponseWidthInterceptorChain方法,该方法为具体的根据请求获取响应部分,留着后面 ...
- 深入理解OkHttp源码(三)——网络操作
这篇博客侧重于了解OkHttp的网络部分,包括Socket的创建.连接,连接池等要点.OkHttp对Socket的流操作使用了Okio进行了封装,本篇博客不做介绍,想了解的朋友可以参考拆轮子系列:拆O ...
- 深入理解OkHttp源码(二)——获取响应
首先先看一张流程图,该图是从拆轮子系列:拆 OkHttp 中盗来的,如下: 在上一篇博客深入理解OkHttp源码(一)——提交请求中介绍到了getResponseWithInterceptorChai ...
随机推荐
- goquery 添加header 发起请求
goquery 添加header 发起请求 我们知道使用net/http 很容易发起GET or POST 请求:并且在发起http请求时候,可以很容易的对header进行干预 例如: client ...
- 第一章 python介绍、变量、数据类型、流程控制语句等
一.python介绍 1.python的诞生 python是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum(龟叔)于1989年发明,第一个公开发行版发行于1991年. ...
- Mysql-单表查询的操作和注意事项
一. 单表查询的语法 二 .关键字的执行优先级(重点) 三 .简单查询 四 .WHERE约束 五. 分组查询:GROUP BY 六 .HAVING过滤 七 .查询排序:ORDER BY 八 .限制查询 ...
- TensorFlow源码安装
前言 TensorFlow如果能二进制包安装,我真的不想选择自己编译,但是情况不由人,好不容易找到一台服务器,CPU不支持AVX指令集,安装的release版本运行到import tensorflow ...
- mysql explain rows理解
在MySQL性能调试中,常常使用EXPLAIN解释MySQL执行计划,从而用来估算性能耗时.其中,rows用来表示在SQL执行过程中会被扫描的行数,该数值越大,意味着需要扫描的行数,相应的耗时更长.但 ...
- 【转】浏览器输入URL后发生了什么
转自:http://www.cnblogs.com/webdeve/p/7865520.html本文摘要: 输入网址 当我们在浏览器输入网址并回车后,一切从这里开始. 一.DNS域名解析 我们在浏览器 ...
- Java基础小知识1——分别使用字节流和字符流复制文件
在日常使用计算机过程中经常会涉及文件的复制,今天我们就从Java代码的角度,看看在Java程序中文件复制的过程是如何实现的. 1.使用字节流缓冲区复制文件 示例代码如下: import java.io ...
- 错误 C2280 Union : 尝试引用已删除的函数 以及 警告 C4624 “Grade”: 已将析构函数隐式定义为“已删除”的一种解决方法
Union 是C/C++语言中的一种结构类型,用于定义可共享内存的数据变量的一种方式,初次使用Union联合体时可能会遇到以下问题: 错误 C2280 Union : 尝试引用已删除的函数 警告 C4 ...
- 阿里云和腾讯云免费SSL证书 专题
阿里云部署SSL证书 http://www.cnblogs.com/sslwork/p/5984167.html 查找中间证书 为了确保兼容到所有浏览器,我们必须在阿里云上部署中间证书,如果不部署证书 ...
- python之12306自动查票
一.导读 本篇文章所采用的技术仅用于学习.研究,任何其他用途请自行承担后果. 12306自动查票使用到的python库主要是splinter,同时也涉及到查票的城市编码,具体的城市编码请在网络上搜 ...