您的位置:首页 > 理论基础 > 计算机网络

Android6.0新特性----OKHttp请求

2015-12-05 18:48 483 查看
最近新开发项目 网络请求采用Okhttp请求 正好利用周末 对okhttp进行了解 一下,先看官网的介绍:

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that’s efficient by default:

HTTP/2 and SPDY support allows all requests to the same host to share a socket.

Connection pooling reduces request latency (if SPDY isn’t available).

Transparent GZIP shrinks download sizes.

Response caching avoids the network completely for repeat requests.

OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Using OkHttp is easy. Its 2.0 API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

You can try out OkHttp without rewriting your network code. The okhttp-urlconnection module implements the familiar java.net.HttpURLConnection API and the okhttp-apache module implements the Apache HttpClient API.

OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.

简单介绍 有以下几点:

android老版本http请求:

HttpUrlConnection

Apache Hrrp Client

Android 6.0请求:

HttpUrlConnection

OKHttp

OkHttp优势:

1.支持SPDY,共享同一个Socket来处理同一个服务器的所有请求

2.如果SPDY不可用,则通过连接池来减少请求延时

3.无缝的支持GZIP来减少数据流量

4.缓存相应数据来减少重复的网络请求

同时okhttp支持Android2.3以上版本:

介绍完了,开始写代码demo

1.在build.gradle当中添加jar包

2.代码get请求

package demo.yangzc.com.okhttp;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.TextView;

import com.squareup.okhttp.OkHttpClient;

import com.squareup.okhttp.Request;

import com.squareup.okhttp.Response;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private TextView textView;

private TextView text_json;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.text);

text_json = (TextView) findViewById(R.id.text_json);

//1.开启一个子线程,做联网操作

new Thread() {

@Override

public void run() {

get();

}

}.start();

}

private void get() {

//1.创建对象

OkHttpClient okHttpClient = new OkHttpClient();

//2.构建一个请求对象

Request request = new Request.Builder().url(“http://apistore.baidu.com/microservice/cityinfo?cityname=%E5%8C%97%E4%BA%AC“).build();

//3.发送请求

try {

Response response = okHttpClient.newCall(request).execute();

//服务端返回的json串

textView.setText(response+”“);

text_json.setText(“返回的Json:”+response.body().string());

} catch (IOException e) {

e.printStackTrace();

}

}

}

3.效果

3.post请求向服务端传递Json串:

/**
* 发送post请求
*/
private void postJson() {
//1.声明给服务器传递一个json串
//2.创建一个OkhttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//3.创建一个RequestBody 请求体(参数1:数据类型 参数2:传递的Json串)
RequestBody requestBody = RequestBody.create(JSON, json);
//4.创建一个请求对象
Request request = new Request.Builder().
url("http://192.168.0.102:8080/Test")
.post(requestBody)
.build();
//5.发送请求获取响应对象
try {
Response response = okHttpClient.newCall(request).execute();
//6.判断此请求是否成功
if (response.isSuccessful()) {
//7.发送成功后服务端返回内容进行打印
textView.setText(response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}


4.向服务器发送post请求,并且传递相应参数:

/**

* 创建post请求 并且传递相应参数

*/

private void postParams() {

//1.创建一个OkHttpClient对象

OkHttpClient okHttpClient = new OkHttpClient();

//2.构建请求体(可以维护多个字段key values)

RequestBody requestBody = new FormEncodingBuilder()

.add(“platform”, “android”)

.add(“version”, “23”)

.build();

//3.构建一个请求对象

Request request = new Request.Builder().

url(“192.168.0.102:8080/TestParams”).

post(requestBody).build();

//4.将请求发送并获取相应响应

try {

Response response = okHttpClient.newCall(request).execute();

//5.判断此请求是否成功

if (response.isSuccessful()) {

//6.发送成功后服务端返回内容进行打印

textView.setText(response.body().string());

}

} catch (IOException e) {

e.printStackTrace();

}

}

5.完整代码:

package demo.yangzc.com.okhttp;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.widget.TextView;

import com.squareup.okhttp.FormEncodingBuilder;

import com.squareup.okhttp.MediaType;

import com.squareup.okhttp.OkHttpClient;

import com.squareup.okhttp.Request;

import com.squareup.okhttp.RequestBody;

import com.squareup.okhttp.Response;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private TextView textView;

private TextView text_json;

//维护传递给服务端的数据类型

public static final MediaType JSON = MediaType.parse(“application/json;charset=utf-8”);

public static final String json = “{\”errNum\”:0,\”retMsg\”:\”success\”,\”retData\”:{\”cityName\”:\”\u5317\u4eac\”,\”provinceName\”:\”\u5317\u4eac\”,\”cityCode\”:\”101010100\”,\”zipCode\”:\”100000\”,\”telAreaCode\”:\”010\”}}”;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.text);

text_json = (TextView) findViewById(R.id.text_json);

//1.开启一个子线程,做联网操作

new Thread() {

@Override

public void run() {

get();

postJson();

postParams();

}

}.start();

}

/**

* 创建post请求 并且传递相应参数

*/

private void postParams() {

//1.创建一个OkHttpClient对象

OkHttpClient okHttpClient = new OkHttpClient();

//2.构建请求体(可以维护多个字段key values)

RequestBody requestBody = new FormEncodingBuilder()

4000
.add(“platform”, “android”)

.add(“version”, “23”)

.build();

//3.构建一个请求对象

Request request = new Request.Builder().

url(“192.168.0.102:8080/TestParams”).

post(requestBody).build();

//4.将请求发送并获取相应响应

try {

Response response = okHttpClient.newCall(request).execute();

//5.判断此请求是否成功

if (response.isSuccessful()) {

//6.发送成功后服务端返回内容进行打印

textView.setText(response.body().string());

}

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 发送post请求

*/

private void postJson() {

//1.声明给服务器传递一个json串

//2.创建一个OkhttpClient对象

OkHttpClient okHttpClient = new OkHttpClient();

//3.创建一个RequestBody 请求体(参数1:数据类型 参数2:传递的Json串)

RequestBody requestBody = RequestBody.create(JSON, json);

//4.创建一个请求对象

Request request = new Request.Builder().

url(“http://192.168.0.102:8080/Test“)

.post(requestBody)

.build();

//5.发送请求获取响应对象

try {

Response response = okHttpClient.newCall(request).execute();

//6.判断此请求是否成功

if (response.isSuccessful()) {

//7.发送成功后服务端返回内容进行打印

textView.setText(response.body().string());

}

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 发送get请求

*/

private void get() {

//1.创建对象

OkHttpClient okHttpClient = new OkHttpClient();

//2.构建一个请求对象

Request request = new Request.Builder().url(“http://apistore.baidu.com/microservice/cityinfo?cityname=%E5%8C%97%E4%BA%AC“).build();

//3.发送请求

try {

Response response = okHttpClient.newCall(request).execute();

//服务端返回的json串

textView.setText(response + “”);

text_json.setText(“返回的Json:” + response.body().string());

} catch (IOException e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息