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用法对比的更多相关文章

  1. OKHttp源码学习同步请求和异步请求(二)

    OKHttp get private void doGet(String method, String s) throws IOException { String url = urlAddress ...

  2. OKHttp源码解析

    http://frodoking.github.io/2015/03/12/android-okhttp/ Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 A ...

  3. 【转载】okhttp源码解析

    转自:http://www.open-open.com/lib/view/open1472216742720.html https://blog.piasy.com/2016/07/11/Unders ...

  4. Okhttp源码分析--基本使用流程分析

    Okhttp源码分析--基本使用流程分析 一. 使用 同步请求 OkHttpClient okHttpClient=new OkHttpClient(); Request request=new Re ...

  5. 从设计模式角度看OkHttp源码

    前言 说到源码,很多朋友都觉得复杂,难理解. 但是,如果是一个结构清晰且完全解耦的优质源码库呢? OkHttp就是这样一个存在,对于这个原生网络框架,想必大家也看过很多很多相关的源码解析了. 它的源码 ...

  6. OkHttp 源码分析

    在工作中用到封装HTTP传输的OkHTTP,OkHttp是相对成熟的解决方案,同时也是开源项目.本文将从源码角度看下OkHttp是如何实现一些网络操作的. HTTP GET: OkHttpClient ...

  7. 深入理解OkHttp源码(一)——提交请求

    本篇文章主要介绍OkHttp执行同步和异步请求的大体流程.主要流程如下图: 主要分析到getResponseWidthInterceptorChain方法,该方法为具体的根据请求获取响应部分,留着后面 ...

  8. 深入理解OkHttp源码(三)——网络操作

    这篇博客侧重于了解OkHttp的网络部分,包括Socket的创建.连接,连接池等要点.OkHttp对Socket的流操作使用了Okio进行了封装,本篇博客不做介绍,想了解的朋友可以参考拆轮子系列:拆O ...

  9. 深入理解OkHttp源码(二)——获取响应

    首先先看一张流程图,该图是从拆轮子系列:拆 OkHttp 中盗来的,如下: 在上一篇博客深入理解OkHttp源码(一)——提交请求中介绍到了getResponseWithInterceptorChai ...

随机推荐

  1. java之jsp页面语法

    jsp页面相比静态页面html来说,就是多了一些脚本,利用这些脚本来动态地改变页面内容的显示. 1.JSP脚本写法 <% 这里写java代码; %> <%! JSP声明,用来声明变量 ...

  2. 4sumii

    problem description: there is four number list named A,B,C,D; now you should out put the num of  tup ...

  3. 解析xml字符串时报“前言中不允许有内容”错误。

    一,问题出现经过: j基于java语言webservic服务端接收客户端 传来的xml字符串用 解析时总报:org.dom4j.DocumentException: Error on line 1 o ...

  4. Ubuntu下vim中文乱码

    在linux中,用vim打开包含中文的文件时,有可能出现乱码 下面的vim配置方法亲测有效 1. 找到你的vimrc文件,也有可能是.vimrc,我的服务器是vimrc,我改的是 有的说建议不要改全局 ...

  5. 关于HTML5中的sessionStorage和localStorage

    需求: 做项目的时大多数情况下我们需要对请求的数据进行多次复用,为了降低请求次数我们需要对请求的数据进行本地存储: 以前用的cooking来存储为本地数据,HTML5后提出sessioStorage. ...

  6. 读《图解HTTP》有感-(返回结果的HTTP状态码)

    写在前面 HTTP状态码是由服务端产生,用于告诉客户端,服务端处理结果的编码 正文 1.状态码的作用是什么?具有什么特征? 状态码的作用是当客户端向服务器发送请求时,描述服务器的响应结果(如:服务器正 ...

  7. js基础进阶--编的实用技巧(一)

    我的个人博客:http://www.xiaolongwu.cn 在平时的开发中,编码技巧很重要,会让你少写很多代码,起到事倍功半的效果. 下面总结几种简单的技巧,大家共同学习一下 1. 利用+.-./ ...

  8. mac下的readelf和objdump

    ELF文件包括: (1)可重定位的目标文件 (2)可执行的目标文件 (3)可被共享的目标文件 可以用file命令来看目标文件是否是ELF文件 在linux下,用readelf来看ELF头部或者其它各s ...

  9. RestTemplate的设置及使用

    概述 RestTemplate是spring内置的http请求封装,在使用spring的情况下,http请求直接使用RestTemplate是不错的选择. Rest服务端 使用RestTemplate ...

  10. eclipse换了高版本的maven插件后报错:org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project

    在给eclipse换了高版本的maven插件后,引入jar包报如下的错误:  org.apache.maven.archiver.MavenArchiver.getManifest(org.apach ...