码迷,mamicode.com
首页 > 编程语言 > 详细

使用HttpClient测试SpringMVC的接口

时间:2017-03-23 11:33:18      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:default   fast   art   响应   manager   icc   bytes   tpc   span   

转载: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}

使用HttpClient测试SpringMVC的接口

标签:default   fast   art   响应   manager   icc   bytes   tpc   span   

原文地址:http://www.cnblogs.com/ceshi2016/p/6603993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!