Eclipse中使用okhttp进行接口请求

1、在pom.xml中添加如下:

com.squareup.okhttp3

okhttp

3.3.0

2、get请求

private void testGet(String url) {

OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder().url(url).build();

Call call = okHttpClient.newCall(request);

try {

Response response = call.execute();

System.out.println(response.body().string());

} catch (IOException e) {

e.printStackTrace();

}

}

3、post请求

OkHttpClient okHttpClient = new OkHttpClient();

RequestBody body = new FormBody.Builder().add("paper_id", paperid).build();

Request request = new Request.Builder().url(url).addHeader("XX", id)

.addHeader("Content-Type", "application/x-www-form-urlencoded")

.post(body).build();

Call call = okHttpClient.newCall(request);

Response response = call.execute();

String aString = response.body().string();

是不是很简单呢,后续再配上json解析,接口请求就完成了。

你可能感兴趣的:(Eclipse中使用okhttp进行接口请求)