使用前需要在Gradle Script中的build gradle中引入:
compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
- GET
//创建OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
final Request request = new Request.Builder()
.url("http://172.20.192.168:8080/getbookByFrom?name=android基础&price=50")//请求的url
.get()//设置请求方式,get()/post() 查看Builder()方法知,在构建时默认设置请求方式为GET
.build(); //构建一个请求Request对象
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
//异步请求(非主线程)
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code()==200) {
System.out.println(response.body().string());
}
});
- POST(json方式)
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
Book book = new Book();
book.setName("android基础");
book.setPrice(59);
//使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
Gson gson = new Gson();
//使用Gson将对象转换为json字符串
String json = gson.toJson(book);
//MediaType 设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, json);
Request request = new Request.Builder()
.url("http://172.20.192.168:8080/getbookByJson")//请求的url
.post(requestBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});
关于将对象转换为json字符串,除了使用Gson还可以用JSONObject:
public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try {
//example: {'likes':['体育','政治'...]}
jsonObject.put("likes",selectedThemes);
} catch (JSONException e) {
e.printStackTrace();
}
//创建一个RequestBody(参数1:数据类型 参数2传递的json串)
RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());
开发过程中遇到传json需要带上authentication的问题,然后在Stack Overflow上找到了解决方法——使用Interceptor。
import java.io.IOException;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class BasicAuthInterceptor implements Interceptor {
private String credentials;
public BasicAuthInterceptor(String user, String password) {
this.credentials = Credentials.basic(user, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build();
return chain.proceed(authenticatedRequest);
}
}
这样就把username和password放进了authentication里。然后把这个Interceptor加到OkHttpClient就可以了。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicAuthInterceptor(username, password))
.build();
网友评论