使用HttpClient测试SpringMVC的接口

最近在写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}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值