轉載:http://blog.csdn.net/tmaskboy/article/details/52355591html
最近在寫SSM建立的Web項目,寫到一個對外接口時須要作測試,接受json格式的數據。在線測試須要放公網地址,無奈localhost沒法訪問,測試工具須要安裝,不想折騰,想到寫爬蟲的時候用到的HttpClient能夠發Post請求,因而進行了嘗試。java
1.編寫請求代碼
因爲接口接受json類型的數據,所以構造了對應的實體類,而後使用fastjson轉爲json,加到請求頭中。apache
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幫助類json
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(); } }
而後就能夠運行了。api
參數:{"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}