当前位置 博文首页 > 莫忘、初心:HttpClient 工具类
使用HttpClient实现java后台http请求主要有三个注意点,
请求参数类型
参数转换
请求头部设置
配置参数类型
/**
* @author zhaosongbin
* @date 2019/4/2 11:19
*/
public class ContentType {
public static String x_www_form_urlencoded = "application/x-www-form-urlencoded";
public static String json = "application/json";
}
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.entity.ByteArrayEntity;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* httpclient 后台请求http工具类
* @author zhaosongbin
* @date 2019/4/2 14:17
*/
public class HttpClientUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* get请求
*
* @param url
* @param token
* @return
*/
public static String get(String url, String token) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {
if (token != null && !"".equals(token)) {
httpGet.addHeader("Authorization", "Bearer " + token);
} else {
logger.warn("http--get方法--token为空");
}
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
} catch (ClientProtocolException e) {
logger.error("http--get方法--ClientProtocolException异常");
e.printStackTrace();
} catch (IOException e) {
logger.error("http--get方法--IOException异常");
e.printStackTrace();
}
logger.error("http--get方法--失败");
return null;
}
/**
* post请求
*
* @param url
* @param param
* @param type
* @param token
* @return java.lang.String
* @author zhaosongbin
* @date 2019/4/3
*/
public static String post(String url, String param, String type, String token) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
if (token != null && !"".equals(token)) {
httpPost.addHeader("Authorization", "Bearer " + token);
} else {
logger.warn("http--post方法--token为空");
}
if (param != null && !"".equals(param)) {
httpPost.addHeader("Content-Type", type);
contentType(param, type, httpPost);
} else {
logger.warn("http--post方法--param为空");
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
return responseContent;
} catch (ClientProtocolException e) {
logger.error("http--post方法--ClientProtocolException异常");
e.printStackTrace();
} catch (IOException e) {
logger.error("http--post方法--IOException异常");
e.printStackTrace();
}
logger.error("http--post方法--失败");
return null;
}
/**
* 判断参数类型,传参模式
*
* @param param
* @param type
* @param httpPost
* @return void
* @author zhaosongbin
* @date 2019/4/3
*/
private static void contentType(String param, String type, HttpPost httpPost) {
try {
if (type.equals(ContentType.json)) {
httpPost.setEntity(new StringEntity(param));
} else if (type.equals(ContentType.x_www_form_urlencoded)) {
httpPost.setEntity(new ByteArrayEntity(param.getBytes()));
}
} catch (Exception e) {
logger.error("ContentType 判断方法异常");
e.printStackTrace();
}
}
}
/**
* 将java对象转换为json格式字符串
* @param obj
* @return json string
*/
public static String objToJson(Object obj) {
ObjectMapper om = new ObjectMapper();
try {
String json = om.writeValueAsString(obj);
return json;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//string 转json数组
String name = "张三";
String age = "18";
String sex = "男";
String json = "{\"name\":\"" + name + "\"," +
"\"age \":\"" + age + "\"," +
"\"sex \":\"" + sex + "\",}";
/**
* @author zhaosongbin
* @date 2019/4/19
*/
public class User {
private String name;
private String age;
private String sex;
@Override
public String toString() {
return "name=" + name + "&" +
"age=" + age + "&" +
"sex=" + sex + "&";
}
//get set 略....
}
cs