HttpClient发送POST请求,SpringMVC接收的问题。

J2EE 码拜 9年前 (2015-04-05) 1371次浏览 0个评论
 

发送代码:

public static void main(String[] args) throws Exception {
        HttpClient client = new DefaultHttpClient();
        String path = "http://localhost:8080/TestAnnotationConfig/b";
        HttpPost post = new HttpPost(path);
        Vendor v = new Vendor();
        v.setName("传输数据");
        v.setDescription("数据传输");
        v.setCreateDate(new Date());
        v.setId(20);
        String content = JSONBinder.binder(Vendor.class).toJSON(v);
        StringEntity entity = new StringEntity(content);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        System.out.println("响应状态码:" + response.getStatusLine().getStatusCode());
        InputStream is = response.getEntity().getContent();
        String text = StreamUtil.readInputStream(is);
        System.out.println("服务器端响应的数据:" + text);
    }

服务器端接收的代码:

@RequestMapping(value = "/b", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String b(@RequestBody Vendor v) {
        System.out.println("客户端发送的数据:" + v);
        return "success";
    }

执行代码报错415。请问怎么回事?
Jackson的HttpMessageConverter我已经配置了,从服务器端返回数据测试已通过,现在就是朝服务器端发送json,报错415。

大神求解,叩谢。

HttpClient发送POST请求,SpringMVC接收的问题。
String content = JSONBinder.binder(Vendor.class).toJSON(v);

不要转 string 直接发对象

HttpClient发送POST请求,SpringMVC接收的问题。
引用 1 楼 u011278496 的回复:

String content = JSONBinder.binder(Vendor.class).toJSON(v);

不要转 string 直接发对象

StringEntity只能接受字符串参数啊,对象怎么直接发送呢?

HttpClient发送POST请求,SpringMVC接收的问题。
代码看起来没什么问题,什么版本的springmvc?
HttpClient发送POST请求,SpringMVC接收的问题。
35分
	// 设置HTTP POST请求参数必须用NameValuePair对象
Gson g = new Gson();
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                               //Map键是param,  值是实体
				params.add(new BasicNameValuePair("param", g.toJson(entity)));
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
				// 设置HTTP POST请求参数
				httpPost.setEntity(entity);
HttpClient发送POST请求,SpringMVC接收的问题。
解决了吗  怎么解决的

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明HttpClient发送POST请求,SpringMVC接收的问题。
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!