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 ...
随机推荐
- 基于jQuery的AJAX实现三级联动菜单
最近学习jQuery,所以就写了一个关于中国省市县/区的三级联动菜单,权当相互学习,相互促进,特此记录. 下面是嵌套js的html文件: <!DOCTYPE html> <html ...
- The Beam Model:Stream & Tables翻译(上)
本文由 网易云发布. 作者:周思华 本篇文章仅限内部分享,如需转载,请联系网易获取授权. 本文尝试描述Beam模型和Stream & Table理论间的关系(前者描述于数据流模型论文.the ...
- Http 状态码(status code)常用总结
本来计划写一篇浏览器错误码使用的详细总结,近来想了想,第一这不是很深入的知识点.主要还是一种规定:第二对常用的几种的一个使用场景已经有所了解了,所以今天就写一个简单的汇总,并黏贴常用几个错误码的介绍在 ...
- 从GitHub中整理出来的15个最受欢迎的Python开源框架,你喜欢哪个
从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python Web应用开发框架 Djang ...
- 分布式配置管理平台XXL-CONF
<分布式配置管理平台XXL-CONF> 一.简介 1.1 概述 XXL-CONF 是一个分布式配置管理平台,提供统一的配置管理服务.现已开放源代码,开箱即用. 1.2 特性 1. ...
- oozie: GC overhead limit exceeded 解决方法
1.异常表现形式 1) 提示信息 Error java.lang.OutOfMemoryError: GC overhead limit exceeded 2)提示出错 Erro ...
- 页面标准文档流、浮动层、float属性(转)
CSS float 浮动属性介绍 float属性:定义元素朝哪个方向浮动. 1.页面标准文档流.浮动层.float属性 1.1 文档流 HTML页面的标准文档流(默认布局)是:从上到下,从左到右,遇块 ...
- Flask入门之触发器,事件,数据迁移
SQLAlchemy Core和SQLAlchemy ORM都具有各种各样的事件挂钩: 核心事件 - 这些在 Core Events中描述,并包括特定于连接池生命周期,SQL语句执行,事务生命周期以及 ...
- FineReport启动后访问404
近期将FineReport以嵌入式方式部署在Tomcat8上,启动服务后,点击导出下载出现HTTP ERROR 404情况: 百思不得其解啊,纠结了好几天: 后查看原部署Tomcat6服务器的cata ...
- 【机器学习】使用gensim 的 doc2vec 实现文本相似度检测
环境 Python3, gensim,jieba,numpy ,pandas 原理:文章转成向量,然后在计算两个向量的余弦值. Gensim gensim是一个python的自然语言处理库,能够将文档 ...