最近需要用到許多在后台發送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(); }