1 实现类
package http;
import okhttp3.*;
import java.io.IOException;
public class HttpClient {
public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
public static String httpGet(String url) throws IOException {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = httpClient.newCall(request).execute();
return response.body().string();
}
public static String httpPost(String url, String json) throws IOException {
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = httpClient.newCall(request).execute();
return response.body().string();
}
}
2 测试代码
package http;
import java.io.IOException;
public class OkhttpTest {
public static void main(String[] args) throws IOException {
String url = "http://www.baidu.com"
String body = HttpClient.httpGet(url);
System.out.println(body);
}
}