您的位置:首页 > 理论基础 > 计算机网络

HttpClient + PostMethod 发送post消息

2015-08-25 09:47 471 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaojian0910/article/details/84738910

发送带参数的http消息

public static String post(String requestBody, String url)
{
String responseMsg = "";
HttpClient httpClient = new HttpClient();

PostMethod method = new PostMethod(url);
Header header = new Header();
header.setName("contentType");
header.setValue("text/html;charset=UTF-8");
method.setRequestHeader(header);
method.addParameter("requestBody", requestBody);
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + "UTF-8");
try
{
httpClient.executeMethod(method);
responseMsg = method.getResponseBodyAsString().trim();
// 打印服务器返回的状态
log.info(method.getStatusLine());
// 打印返回的信息
log.info(responseMsg);
} catch (HttpException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
// 释放连接
method.releaseConnection();
}

return responseMsg;
}

服务器接受参数

package com.zj.service.conroller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.zj.service.dto.User;
import com.zj.service.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
@Resource
private UserService userService;

@RequestMapping("add")
public String userAdd(String requestBody)
{
System.out.println(requestBody);
User user = JSON.parseObject(requestBody, User.class);
userService.addUser(user);

return null;
}
}

 参数要名称一致

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: