maven 依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
get 请求
带参数的 get 请求
public static void getXijingTemplate() throws Exception {
String url = "http://www.example.com";
URIBuilder builder = new URIBuilder(url);
builder.addParameter("username", "username");
builder.addParameter("password", "123456");
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpGet);
System.out.println(decodeUnicode(EntityUtils.toString(response.getEntity(), Consts.UTF_8)));
}
post 请求
带参数的 post 请求
public static void executeGet() throws IOException {
String url = "http://www.example.com";
JSONObject param = JSONObject.parseObject(params);
StringEntity entity = new StringEntity(param.toJSONString(), Charset.forName("UTF-8"));
HttpPost post = new HttpPost(url);
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println(decodeUnicode(EntityUtils.toString(response.getEntity(), Consts.UTF_8)));
}
有的请求返回的结果字符是 unicode 类型的,对于中文,不便于排查问题,可以使用以下的方法处理返回的结果:
//Unicode转中文
public static String decodeUnicode(final String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 0; i < hex.length; i++) {
try {
// 汉字范围 \u4e00-\u9fa5 (中文)
if(hex[i].length()>=4){//取前四个,判断是否是汉字
String chinese = hex[i].substring(0, 4);
try {
int chr = Integer.parseInt(chinese, 16);
boolean isChinese = isChinese((char) chr);
//转化成功,判断是否在 汉字范围内
if (isChinese){//在汉字范围内
// 追加成string
string.append((char) chr);
//并且追加 后面的字符
String behindString = hex[i].substring(4);
string.append(behindString);
}else {
string.append(hex[i]);
}
} catch (NumberFormatException e1) {
string.append(hex[i]);
}
}else{
string.append(hex[i]);
}
} catch (NumberFormatException e) {
string.append(hex[i]);
}
}
return string.toString();
}
/**
* 判断是否为中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}