服务端代码如下
@RequestMapping(value = "/data", method = RequestMethod.GET)
public void getList(HttpEntity<String> entity){
         String dataJson = entity.getBody();
String typeStr = entity.getHeaders().getFirst("type");
            /*
               处理
            */
}
请求的URL地址是http://localhost:8080/restful/data
消息为
String reportJson ="json内容......"
String reportType = "类型";
请问客户端的GET请求该如何来构造?

解决方案 »

  1.   


    String reportJson ="json内容......"
    String reportType = "类型";
    HttpURLConnection con = 
    (HttpURLConnection)new URL("http://localhost:8080/restful/data").openConnection();
    con.setRequestMethod("POST"); //设置为post提交
    con.setRequestProperty("type", reportType ); //设置header["类型"]
    BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
    bout.write(reportJson);
    bout.flush();
    bout.close();        // 取得输入流,并使用Reader读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));        String lines;
            while ((lines = reader.readLine()) != null) {
                System.out.println(lines);
            }
            reader.close();由于你的action有用 entity.getBody(); 来获取请求体 所以 应该用post method = RequestMethod.POST
      

  2.   


    如果坚持用GET方式,也没问题
    那就把这句删了吧 con.setRequestMethod("POST");
      

  3.   

    cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
    设置true以后就
    Server returned HTTP response code: 405 for URL
      

  4.   

    另外cscript你知道怎么用RestTemplate里的get方法来构造本帖的这消息头和消息体吗?
      

  5.   

    RestTemplate 的话 参考下面,也是刚刚参考RestTemplate文档写的,没测试
    http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html可用的话,楼主结贴或加分吧,呵呵还是那句话,最好用post,因为你需要提交的json内容是通过entity.getBody();获取的
    get的entity.getBody();是空的至于get和post的区别,我就不科普了,百度一大堆
    String reportJson ="json内容......"
    String reportType = "类型";HttpHeaders headers = new HttpHeaders();
    headers.set("type", reportType);
    HttpEntity<String> entity = new HttpEntity<String>(reportJson, headers);
    String respSrc = template.postForObject("http://localhost:8080/restful/data", entity, String.class);
      

  6.   

    你一定要用get的话 你看RestTemplate文档中getForObject和getForEntity都没有参数给你设置请求头原因5楼我已经说了,如果你一定要用get的话可以试试,没有测试,你自己看吧
    String reportJson ="json内容......"
    String reportType = "类型";HttpHeaders headers = new HttpHeaders();
    headers.set("type", reportType);
    HttpEntity<String> entity = new HttpEntity<String>(reportJson, headers);
    ResponseEntity<String> respEntity = template.exchange(new URI("http://localhost:8080/restful/data"), RequestMethod.GET, entity, String.class);
    System.out.print(respEntity.getBody());