okhttp实现 httpget 和 httppost 的java实现

来源:互联网 发布:ifashion淘宝什么意思 编辑:程序博客网 时间:2024/05/21 07:50

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);    }}