轉載:http://blog.csdn.net/tmaskboy/article/details/52355591
最近在寫SSM創建的Web項目,寫到一個對外接口時需要做測試,接受json格式的數據。在線測試需要放公網地址,無奈localhost無法訪問,測試工具需要安裝,不想折騰,想到寫爬蟲的時候用到的HttpClient可以發Post請求,於是進行了嘗試。
1.編寫請求代碼
由於接口接受json類型的數據,因此構造了對應的實體類,然后使用fastjson轉為json,加到請求頭中。
String url = "http://localhost:8080/api/hcp/get"; Map<String, Object> map = new HashMap<String, Object>(); //構造參數 map.put("token", "Tq0kzItQdol1pO4T"); String result = APITest.API(url, JSONObject.toJSONString(map)); //使用FastJson轉為json格式 System.out.println(result);
2.APITest.Java幫助類
public class APITest { /** * * @param 要請求的接口地址 * @param post參數 * @return 接口返回的數據 * @throws IOException */ public static String API(String url,String parameters) throws IOException{ System.out.println("參數:"+parameters); HttpClient httpclient = new DefaultHttpClient(); //新建Http post請求 HttpPost httppost = new HttpPost(url); //登錄鏈接 httppost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8"))); httppost.addHeader("Content-type","application/json; charset=utf-8"); httppost.setHeader("Accept", "application/json"); //處理請求,得到響應 HttpResponse response = httpclient.execute(httppost); //打印返回的結果 HttpEntity entity = response.getEntity(); // Header[] map = response.getAllHeaders(); StringBuilder result = new StringBuilder(); if (entity != null) { InputStream instream = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(instream)); String temp = ""; while ((temp = br.readLine()) != null) { String str = new String(temp.getBytes(), "utf-8"); result.append(str).append("\r\n"); } } return result.toString(); } }
然后就可以運行了。
參數:{"token":"Tq0kzItQdol1pO4T"} log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.BasicClientConnectionManager). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. {"reason":"Token已過期","error_code":1,"result":null}