`
zhaojian0910
  • 浏览: 46494 次
社区版块
存档分类
最新评论

HttpClient + PostMethod 发送post消息

 
阅读更多

发送带参数的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;
	}
}

 参数要名称一致

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics