在网上发现很多示例都达不到如下要求
1、 get POST 传参可以带中文
2、 返回值是json格式
阿里的com.alibaba.druid.util.HttpClientUtils 也无法得到服务器返回的json格式的数据,故自己写了一个,仓促写的,里面还没有写超时的代码,如有优化之处,敬请指正!
package io.backpack.member.util.network;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* <pre class="code"><b>{@code
* Title: get和post请求,可以含有中文, 假定返回值都是json格式的数据
*
* 服务提供方 可以参见 https://gitee.com/prgs/highlight_springmvc4.git 部署到tomcat即可运行, 假定端口是8080
*
* }</pre>
* @author haobin
* @date 2018年7月16日 下午8:42:18
*/
public class HttpUtils {
/**
* <pre class="code"><b>{@code
* Title: 发送 get请求 已测试 可以传中文
*
* }</pre>
* @param url
* @return 返回json格式的数据
* @author haobin
* @date 2018年7月16日 下午8:34:49
*/
public static String get(String url) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String context = "";
try {
URL uRL = new URL(url);
URI uRI = new URI(uRL.getProtocol(), uRL.getHost() + ":" + uRL.getPort(), uRL.getPath(), uRL.getQuery(),
null);
// 创建httpget.
HttpGet httpget = new HttpGet(uRI);
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容 ,转换为utf-8格式,避免所传内容包含汉字乱码
context = EntityUtils.toString(entity, "UTF-8");
System.out.println(context);
}
response.close();
return context;
} catch (Exception e) {
e.printStackTrace();
return "Exception";
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* <pre class="code"><b>{@code
* Title:
* 发送POST请求, 已测试,可以传递中文
* 注意, 当服务器端返回的是空字符串时, 本方法返回值将会是null
*
*
* 补充:
如果 服务器提供方返回的json类似于:
{
"id": 1111,
"name": "嘿嘿",
"passwd": "123456",
"data": {
"aa": "第一",
"bb": "这是第二名"
}
}
则调用方想获取aa的值可以这样写:
JSONObject jSONObject = HttpUtils.doPost(url, XXXX);
if (null != jSONObject) {
System.out.println(jSONObject.getJSONObject("data").getString("aa")+ ", " + jSONObject.getString("name"));
}
*
* }</pre>
* @param url url地址,随业务要求,可以附带中文参数
* @param bodyMap POST Body要发送的数据, 以Map<String, String>格式出现; 如果没有,允许为null
* @return 返回json格式的数据
* @author haobin
* @date 2018年7月16日 下午2:58:30
*/
public static JSONObject doPost(String url, Map<String, String> bodyMap) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String result = null;
com.alibaba.fastjson.JSONObject jSONObject = null;
try {
// 2018-07-16 haobin: 解决 110行 如果bodyMap为Null 时运行报错的问题
if (null == bodyMap) {
bodyMap = new HashMap<String, String>();
}
// 2018-07-16 haobin: 最后一个参数不能省略,否则会导致服务器端接收到的中文数据出现乱码
StringEntity s = new StringEntity(JSON.toJSONString(bodyMap), "UTF-8"); //110
s.setContentEncoding("UTF-8");
s.setContentType("application/json");// 发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
result = EntityUtils.toString(res.getEntity());// 返回json格式:
jSONObject = JSON.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jSONObject;
}
private static void testPost() {
String url = "http://localhost:8080/highlight_springmvc4/anno/obj3?address=北京";
Map<String, String> m = new HashMap<String, String>();
m.put("id", "1111");
m.put("name", "张三");
m.put("passwd", "123456");
JSONObject jSONObject = doPost(url, m);
if (null != jSONObject) {
System.out.println(jSONObject.toString());
System.out.println(jSONObject.toJSONString());
System.out.println(jSONObject.get("id") + ", " + jSONObject.getString("name"));
}
}
/**
* 经测试发现, com.alibaba.druid.util.HttpClientUtils 无法得到服务器返回的json格式的数据
*/
// public static void testAliBabaPost(){
// HttpClientUtils.post("http://localhost:8080/highlight_springmvc4/anno/obj3?address=beijing",
// "id=1111&name=qiaofeng&passwd=123qweasd", 6000);
// }
private static void testGet() {
String url = "http://localhost:8080/highlight_springmvc4/anno/requestParam2?passwd=33&name=zhangsan";
String url2 = "http://localhost:8080/highlight_springmvc4/anno/obj1?name=大刀王五&id=33&passwd=123qweasd&address=深圳";
String s1 = get(url2);
System.out.println("s1 = " + s1);
}
public static void main(String[] args) {
// testAliBabaPost();
testPost();
// testGet();
}
}