Java实现http客户端请求

依赖配置pom.xml

<!-- httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>

Get请求

/**
 * 抓取指定网页,返回文本信息。
 * @param url 网页地址
 * @param code 指定网页解析编码
 * @return 网页文本
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String httpGet(String url, String code) throws Exception {
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(10000)
            .setSocketTimeout(10000)
            .setConnectionRequestTimeout(10000)
            .build();
    HttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(url);
    get.setConfig(config);
    HttpResponse response = client.execute(get);
    return EntityUtils.toString(response.getEntity(), code);
}

/**
 * 抓取指定网页,返回文本信息。默认utf-8编码方式解析文本。
 * @param url 网页地址
 * @return 网页文本
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String httpGet(String url) throws Exception {
    return httpGet(url, "utf-8");
}

Post请求

/**
 * 发送HTTP请求,并设置post参数。
 * @param ur 请求地址
 * @param data 参数键值对
 * @return 获取响应
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String httpPost(String url, Map<String, Object> data) throws ClientProtocolException, IOException {
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(10000)
            .setSocketTimeout(10000)
            .setConnectionRequestTimeout(10000).build();
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setConfig(config);
    post.setHeader("Content-Type", "application/json;charset=UTF-8");
    post.setEntity(new StringEntity(JSONObject.toJSONString(data)));
    HttpResponse response = client.execute(post);
    return EntityUtils.toString(response.getEntity(), "utf-8");
}
上一篇:java int与integer的区别


下一篇:转发与重定向的区别(显示页面)