发送HTTP请求有很多包可以实现,这里介绍OkHttpClient3
(想了解其他一些实现方法和他们之间的区别,请戳:
http://blog.csdn.net/zhangcanyan/article/details/51793951
)
maven配置如下
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.8.0</version>
</dependency>
Get请求如下:
public void OkHttpGet(String url) {
OkHttpClient okHttpClient = new OkHttpClient();
//不配url方法会报错,肯定要有访问地址的嘛
//.Builder是Request内部类 .url()返回Builder .build()返回Request对象
Request request = new Request.Builder()
//.addHeader("a", "b")//.addHeader添加键值对header信息
//.get()//可加可不加
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
//http状态码
System.out.println(response.code());
//response的头信息
System.out.println(response.headers().toString());
//请求响应时间,收到时间减去发送的时间,单位毫秒
System.out.println(response.receivedResponseAtMillis()-response.sentRequestAtMillis());
} catch (IOException e) {
e.printStackTrace();
}
}
可以反过来记忆需要用到的方法response需要call.execute->call需要okhttpclient对象和request,request中添加需要的参数和地址
注意:Request.Builder中build方法对url进行判断,如果为空就会报
"url == null"这个错
public Request build() {
if(this.url == null) {
throw new IllegalStateException("url == null");
} else {
return new Request(this);
}
}
Get方法结果
中国天气网接口例子
Post请求如下:
public void OkHttpPost(String url){
//ssl认证重写
OkHttpClient okHttpClient=new OkHttpClient.Builder().hostnameVerifier(
new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
).build();
RequestBody requestBody=new FormBody.Builder()
.add("oldPassword","111111")
.add("newPassword","111111")
.build();
Request request=new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Cookie","JSESSIONID=299571E0E40DA6E9962E41B87A669BBB")
.addHeader("content-type", "application/json")
.addHeader("cache-control", "no-cache")
.build();
Call call=okHttpClient.newCall(request);
try {
Response response=call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
和Get方法差不多。区别在于Request中需要添加.post请求,参数是requestBody
所以要实例requestbody对象,并且添加参数。FormBody是RequstBody的子类,里面有add添加参数方法
注意:如果碰到有些网站登录时会说 网站不安全之类的 会报如下错误
这里需要重写HostnameVerifier中的verify方法,强制它认证成功
详细操作和原理请戳:
http://blog.csdn.net/notHeadache/article/details/52133468
结果:
网友评论