转载: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}
时间: 2024-10-16 08:53:05