前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >使用HttpClient测试SpringMVC的接口

使用HttpClient测试SpringMVC的接口

作者头像
geekfly
发布于 2022-05-06 11:35:34
发布于 2022-05-06 11:35:34
34100
代码可运行
举报
文章被收录于专栏:geekflygeekfly
运行总次数:0
代码可运行

最近在写SSM创建的Web项目,写到一个对外接口时需要做测试,接受json格式的数据。在线测试需要放公网地址,无奈localhost无法访问,测试工具需要安装,不想折腾,想到写爬虫的时候用到的HttpClient可以发Post请求,于是进行了尝试。

1.编写请求代码 由于接口接受json类型的数据,因此构造了对应的实体类,然后使用fastjson转为json,加到请求头中。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    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帮助类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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();
    }
}

然后就可以运行了。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
参数:{"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}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-08-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档