[java,2018-01-16] HttpClient发送、接收 json 请求

最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据。

就抽取出来写了一个帮助类:

首先判断发送的数据类型是json还是xml:

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;


    /**
* 判断是否是json结构
*/
public static boolean isJson(String value) {
try {
JSONObject.parseObject(value);
} catch (JSONException e) {
return false;
}
return true;
} /**
* 判断是否是xml结构
*/
public static boolean isXML(String value) {
try {
DocumentHelper.parseText(value);
} catch (DocumentException e) {
return false;
}
return true;
}

判断之后就设置对应的属性,然后执行post方法:

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
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.HttpClients;
import org.apache.http.util.EntityUtils;    private static int connectionTimeout = 1000;// 连接超时时间,毫秒
private static int soTimeout = 30000;// 读取数据超时时间,毫秒
/** HttpClient对象 */
private static CloseableHttpClient httpclient = HttpClients.
custom().disableAutomaticRetries().build();
/*** 超时设置 ****/
private static RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(soTimeout)
.setConnectTimeout(connectionTimeout)
.build();//设置请求和传输超时时间   /**
* 根据给定的URL地址和参数字符串,以post方法调用,如果成功返回true,如果失败返回false
*
* @param url String url地址,不含参数
* @param param Map<String, Object> 参数字表单
* @return boolean true-成功,false失败,如果返回成功可以getStrGetResponseBody()
* 获取返回内容字符串,如果失败,则可访问getErrorInfo()获取错误提示。
*/
public String executePostMethod(String strURL, String param) {
System.out.println("step into executePostMethod");
String strResult = "";
HttpPost post = new HttpPost(strURL);
post.setConfig(requestConfig);
StringEntity entity; try {
System.out.println("step into try"); if(isJson(param)){
System.out.println("it is json");
entity = new StringEntity(param,"utf-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
}else if(isXML(param)){
System.out.println("it is xml");
entity = new StringEntity(param,"utf-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("text/xml");
post.setEntity(entity);
}else{
entity = new StringEntity(param,"utf-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
} //发起请求
HttpResponse httpResponse = httpclient.execute(post);
// 请求结束,返回结果
strResult = EntityUtils.toString(httpResponse.getEntity());
System.out.println(strResult);
} catch (Exception e) {
e.printStackTrace();
}
return strResult;
}

另附上map转为xml和json的方法:

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;

   /**
* 将map转换为xml
* @param map
*/
private static String convertMap2Xml(Map<String,String> map) {
Set<Entry<String,String>> entrys = map.entrySet();
Iterator<Entry<String,String>> iter = entrys.iterator();
Document doc = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("xml");
while(iter.hasNext()) {
Entry<String,String> entry = iter.next();
Element key = DocumentHelper.createElement(entry.getKey());
key.addCDATA(entry.getValue());
root.add(key);
}
doc.add(root);
return doc.asXML();
}   /**
* 将map转换为json
* @param map
*/
private static String convertMap2Json(Map<String,String> map) {
JSONObject json = JSONObject.parseObject(map.toString());
return json.toString();
}

http接受json格式的数据

public String getJsonData(HttpServletRequest request) {
System.out.println(request.getCharacterEncoding());
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
return sb.toString();
}
 
上一篇:使用firefox插件httperrequest,模拟发送及接收Json请求 【转】


下一篇:centos6 nginx 安装【转】