OKHttp通信使用
Posted xiaoleiacm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OKHttp通信使用相关的知识,希望对你有一定的参考价值。
概念:
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());
);
以上是关于OKHttp通信使用的主要内容,如果未能解决你的问题,请参考以下文章