版权声明:

欢迎转载,但请保留文章原始出处

作者:GavinCT

出处:http://www.cnblogs.com/ct2011/p/4001708.html

为什么需要一个HTTP库

Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。

关于HttpURLConnection和HttpClient的选择>>官方博客

尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。

OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了。所以我们更有理由相信OkHttp的强大。

入门

官方资料

官方介绍

github源码

使用范围

OkHttp支持Android 2.3及其以上版本。

对于Java, JDK1.7以上。

jar包准备

官方介绍页面有链接位置。这里把下载链接也写在下面。

OkHttp

Okio

基本使用

HTTP GET

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}

Request是OkHttp中访问的请求,Builder是辅助类。Response即OkHttp中的响应。

Response类:

public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

response.body()返回ResponseBody类

可以方便的获取string

public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
IOException

当然也能获取到流的形式:

public final InputStream byteStream()

HTTP POST

POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}

使用Request的post方法来提交请求体RequestBody

POST提交键值对

很多时候我们会需要通过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来做这件事情。

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException { RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build(); Request request = new Request.Builder()
.url(url)
.post(body)
.build(); Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}

总结

通过上面的例子我们可以发现,OkHttp在很多时候使用都是很方便的,而且很多代码也有重复,因此特地整理了下面的工具类。

注意:

  • OkHttp官方文档并不建议我们创建多个OkHttpClient,因此全局使用一个。 如果有需要,可以使用clone方法,再进行自定义。这点在后面的高级教程里会提到。
  • enqueue为OkHttp提供的异步方法,入门教程中并没有提到,后面的高级教程里会有解释。
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import cn.wiz.sdk.constant.WizConstant;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response; public class OkHttpUtil {
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
static{
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
}
/**
* 该不会开启异步线程。
* @param request
* @return
* @throws IOException
*/
public static Response execute(Request request) throws IOException{
return mOkHttpClient.newCall(request).execute();
}
/**
* 开启异步线程访问网络
* @param request
* @param responseCallback
*/
public static void enqueue(Request request, Callback responseCallback){
mOkHttpClient.newCall(request).enqueue(responseCallback);
}
/**
* 开启异步线程访问网络, 且不在意返回结果(实现空callback)
* @param request
*/
public static void enqueue(Request request){
mOkHttpClient.newCall(request).enqueue(new Callback() { @Override
public void onResponse(Response arg0) throws IOException { } @Override
public void onFailure(Request arg0, IOException arg1) { }
});
}
public static String getStringFromServer(String url) throws IOException{
Request request = new Request.Builder().url(url).build();
Response response = execute(request);
if (response.isSuccessful()) {
String responseUrl = response.body().string();
return responseUrl;
} else {
throw new IOException("Unexpected code " + response);
}
}
private static final String CHARSET_NAME = "UTF-8";
/**
* 这里使用了HttpClinet的API。只是为了方便
* @param params
* @return
*/
public static String formatParams(List<BasicNameValuePair> params){
return URLEncodedUtils.format(params, CHARSET_NAME);
}
/**
* 为HttpGet 的 url 方便的添加多个name value 参数。
* @param url
* @param params
* @return
*/
public static String attachHttpGetParams(String url, List<BasicNameValuePair> params){
return url + "?" + formatParams(params);
}
/**
* 为HttpGet 的 url 方便的添加1个name value 参数。
* @param url
* @param name
* @param value
* @return
*/
public static String attachHttpGetParam(String url, String name, String value){
return url + "?" + name + "=" + value;
}
}

高级

高级属性其实用的不多,这里主要是对OkHttp github官方教程进行了翻译。

请看我的另一篇博客:OkHttp使用进阶 译自OkHttp Github官方教程

OkHttp使用介绍的更多相关文章

  1. 简单的OkHttp使用介绍

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  2. okhttp 基本介绍

    资料汇总 官网:http://square.github.io/okhttp/ 文档:https://github.com/square/okhttp/wiki GitHub:https://gith ...

  3. OKHttp的容易使用

    OKHttp的简单使用 一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结 ...

  4. OkHttp使用教程

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  5. OkHttp使用进阶 译自OkHttp Github官方教程

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/3997368.html 没有使用过OkHttp的,可以先看Ok ...

  6. OkHttp使用进阶(译自OkHttp官方教程)

    没有使用过OkHttp的,可以先看OkHttp使用介绍 英文版原版地址 Recipes · square/okhttp Wiki 同步get 下载一个文件,打印他的响应头,以string形式打印响应体 ...

  7. OKHttp的简单使用

    一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结了一点东西,与大家分享. ...

  8. 跟我学SpringCloud | 第二十章:Spring Cloud 之 okhttp

    1. 什么是 okhttp ? okhttp 是由 square 公司开源的一个 http 客户端.在 Java 平台上,Java 标准库提供了 HttpURLConnection 类来支持 HTTP ...

  9. 从 http协议角度解析okhttp

    Okhttp 介绍 OkHttp 是 Square 公司开源的一款网络框架,封装了一个高性能的 http 请求库. 支持 spdy.http2.0.websocket 等协议 支持同步.异步请求 封装 ...

随机推荐

  1. 使用JDBC处理Oracle大数据

    一.Oracle中大数据处理 在Oracle中,LOB(Large Object,大型对象)类型的字段现在用得越来越多了.因为这种类型的字段,容量大(最多能容纳4GB的数据),且一个表中可以有多个这种 ...

  2. QueryRunner(common-dbutils.jar)

    QueryRunner update方法:* int update(String sql, Object... params) --> 可执行增.删.改语句* int update(Connec ...

  3. DOCTYPE 中xhtml 1.0和 html 4.01区别分析

    前者相对于后者有以下特性: 1.所有的标记都都要闭合 所有的标记都要闭合,如果是单独不成对的标签,在标签最后加一个"/"来关闭它.例如: <h6>close tag & ...

  4. xml 中转意字符&\/使用方法

    所有 XML 元素都须有关闭标签 在 HTML,经常会看到没有关闭标签的元素: <p>This is a paragraph <p>This is another paragr ...

  5. C++学习基础六——复制构造函数和赋值操作符

    1.什么是复制构造函数 复制构造函数:是构造函数,其只有一个参数,参数类型是所属类的类型,且参数是一个const引用. 作用:将本类的成员变量赋值为引用形参的成员变量. 2.什么是赋值操作符 赋值操作 ...

  6. 日志分析工具ELK配置详解

    日志分析工具ELK配置详解 一.ELK介绍 1.1 elasticsearch 1.1.1 elasticsearch介绍 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分 ...

  7. ASP.NET Web API系列教程目录

    ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...

  8. python(第五步django)

    这是一个关于,web开发的库, 下一步需要重点掌握的是,网页跳转和数据展示,和面向对象的关系的重用的内容 1:目前掌握的是project 的创建,和app的创建, 2:

  9. codeforce div 377

    #include <bits/stdc++.h> using namespace std; #define pb push_back #define lb lower_bound #def ...

  10. word 批量删除书签

    打开word    按住alt+F11 进入vba 界面 Sub test() Dim MyBk As Bookmark For Each MyBk In ActiveDocument.Bookmar ...