httpclient的基本使用代码

1.所需的依赖jar

   <dependency>

      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
   <!--  httpclient缓存 -->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.5</version>
    </dependency>
   <!-- http的mime类型都在这里面 -->
    <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpmime</artifactId>
     <version>4.3.2</version>

    </dependency>

2.代码

package com.zy.httpclient;


import java.io.IOException;
import java.net.URI;
import java.util.Map;


import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * httpclient工具类 
 * 封装了get post 请求方法
 * @author zl
 *
 */
public class HttpClientUtils {
/**
* 带参数的doPost请求
* @param url 请求地址
* @param map 参数
* @return 响应实体字符串
* @throws Exception 
*/
public static String doPost(String url, Map<String, String> map) {


// 使用默认配置的httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 响应
CloseableHttpResponse response = null;
String result = "";
try {
// 参数的构建
URIBuilder buildUri = new URIBuilder(url);
// 设置参数的键和值
if (map != null) {
for (String key : map.keySet()) {
buildUri.addParameter(key, map.get(key));
}
}
URI uri = buildUri.build(); // 构建uri
// 创建post实例
System.out.println(uri);
HttpPost httpPost = new HttpPost(uri);
// 执行请求 获取响应
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {// 如果请求成功
if (response.getEntity() != null) {
result = EntityUtils
.toString(response.getEntity(), "UTF-8");
}
}
} catch (Exception e) {


e.printStackTrace();
} finally {
close(response, httpclient);
}
return result;
}
/**
* 不带参数的post请求
* @param url 请求地址
* @return 
*/
public static String doPost(String url){
return doPost(url,null);
}

/**
* 带参数的get请求
* @param url 请求地址
* @param map 参数集合
* @return 响应实体
*/
public static String doGet(String url, Map<String, String> map) {


// 使用默认配置的httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 响应
CloseableHttpResponse response = null;
String result = "";
try {
// 参数的构建
URIBuilder buildUri = new URIBuilder(url);
// 设置参数的键和值
if (map != null) {
for (String key : map.keySet()) {
buildUri.addParameter(key, map.get(key));
}
}
URI uri = buildUri.build(); // 构建uri
// 创建post实例
System.out.println(uri);
HttpGet httpGet = new HttpGet(uri);
// 执行请求 获取响应
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {// 如果请求成功
if (response.getEntity() != null) {
result = EntityUtils
.toString(response.getEntity(), "UTF-8");
}
}
} catch (Exception e) {


e.printStackTrace();
} finally {
close(response, httpclient);
}
return result;
}

/**
* 不带参数的get请求
* @param url 请求地址
* @return 
*/
public static String doGet(String url){
return doGet(url,null);
}
/**
* 关闭
* @param response
* @param httpclient
*/
private static void close(CloseableHttpResponse response,
CloseableHttpClient httpclient) {
try {
if(response!=null){
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response, httpClient);
        }


        return resultString;
    }


public static void main(String[] args) throws Exception {
/*Map<String,String> map = new HashMap<String, String>();
map.put("username", "zhangsan");
map.put("password", "123456");*/
String reslut = doGet("https://www.baidu.com");
System.out.println(reslut);
}
}

3.构建参数的另一种方式是:

// 创建Http Post请求
            HttpPost httpPost = new HttpPost(url); 

// 创建参数列表

            if (map != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : .keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }

// 执行http请求
            response = httpClient.execute(httpPost);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值