• 使用HttpClient测试SpringMVC的接口


    转载: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("
    ");  
                }  
            }
            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}
  • 相关阅读:
    HTTP 筛选器 DLL C:WindowsMicrosoft.NetFrameworkv4.0.30319aspnet_filter.dll 加载失败。数据是错误。
    win7(iis7)无法加载运行CSS文件的解决方法
    MVC异步消息推送机制
    查看目录下所有文件的行数
    解决 mac全屏时不能隐藏Dock工具栏 killall Dock
    jetty中传java参数(spring-io中的配置项)
    nginx代理前端项目
    【转】mackbook wifi卡死未响应的问题
    WeekMap WeakSet的用途
    每日新知2019-08-23
  • 原文地址:https://www.cnblogs.com/ceshi2016/p/6603993.html
Copyright © 2020-2023  润新知