OKHttp通信使用(一)
2016-06-15 20:20
239 查看
概念:
Android 提供了两种HTTP通信方式:一种是Java原生的Apache的HTTP通信:HttpClient ,另一种是android所使用的HttpURLConnection。作为较为成熟的HTTP通信机制OKHTTP正在取代上述两种HTTP通信方式,在android 4.4版本后,Volley也剔除了HttpURLConnection,改为使用OKHTTP进行通信。它的优势在于更稳定,可以设置多个IP地址进行失败连接问题的处理等等。在进行HTTPS访问时也更加稳定和安全。
下面是OKHTTP的简单应用。主要来自于GitHub:https://github.com/square/okhttp/wiki
OKHTTP支持所有的HTTP请求方式:GET,POST,HEAD.....这里主要是进行GET与POST为例进行介绍。
OKHTTP有两种请求方式:
同步方式:
execute
异步方式:
enqueue
使用方式:
为一下所有函数定义全局变量:private final OkHttpClient client = new OkHttpClient();
GET请求:
使用get请求下载文件,返回的是String。
public void run() throws Exception {Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
使用Get请求JSON数据:
static class Gist {Map<String, GistFile> files;
}
static class GistFile {
String content;
}
private final Gson gson = new Gson();
public void run_JSON() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
System.out.println("11111111111111111111 "+entry.getKey());
System.out.println(entry.getValue().content);
}
}
});
}
POST请求:
使用POST发送一个String型数据:
public static final MediaType MEDIA_TYPE_MARKDOWN= MediaType.parse("text/x-markdown; charset=utf-8"); //content-type
/**
* 发送一个string型数据
* @throws Exception
*/
public void run_string() throws Exception {
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
});
}
使用POST请求发送一个键值对:
/*** 发送一个post键值对参数
* @throws Exception
*/
public void run_keyValue() throws Exception {
RequestBody formBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
});
}
使用POST发送一个数据流:
/*** //发送一个流
* @throws Exception
*/
public void run_Streaming() throws Exception {
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers\n");
sink.writeUtf8("-------\n");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
});
}
相关文章推荐
- 原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/database/493/12549493.shtml
- TCP/IP协议详解(二):建立和关闭连接
- OkHttp网络请求
- 请求网络
- HttpUrlConnection POST请求
- HTTP in iOS你看我就够
- 网络抓包工具Wireshark和Fidder
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- Apache HttpClient
- TCP协议中的三次握手和四次挥手(图解)
- TCP的流量控制和拥塞控制
- 安卓中进行基于Http协议的网络访问基础总结-2
- c++网络编程2:TCP连接概念及编程
- linux网络编程--UDP协议
- Socket编程基础--基于TCP协议的网络编程
- HttpClient连接池的连接保持、超时和失效机制
- adb tcp 调试
- ZK 网址 https://www.zkoss.org/
- 【java爬虫】HttpClient4.5获取网页内容
- HttpClient 在Java项目中的使用详解