java中利用httpClient的post方法请求远程接口

很多情况下,在开发中我们需要请求远程接口,向远程接口发送数据,HttpClient是经常采用的方式

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建PostMethod对象,并指定访问的URL

3. PostMethod对象中通过addParameter()方法添加数据

4. 调用HttpClient对象的executeMethod(postMethod)发送请求,该方法返回一个状态码。

5. 通过返回的状态码判断是否访问成功,不成功解析返回信息

6. 释放连接。无论执行方法是否成功,都必须释放连接

public class HttpUtil {
	public static final String URL = "http://www.baidu.com:1221/Service.asmx/GetCheckdatetime";
	public static String methodPost(JSONArray jsonArray) {
		String response="";// 要返回的response信息
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(URL);
		postMethod.addParameter("Json", jsonArray.toString());// 将表单的值放入postMethod中
		NameValuePair teString=postMethod.getParameter("Json");
		System.out.println(teString);
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);
		} catch (IOException e) {
			e.printStackTrace();
		}
		/**
		 * 执行postMethod
		 * HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
		 * 301或者302
		 */
		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			Header locationHeader = postMethod.getResponseHeader("location");// 从头中取出转向的地址
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
				System.out.println("The page was redirected to:" + location);
				response = methodPost(jsonArray);// 用跳转后的页面重新请求。
			} else {
				System.err.println("Location field value is null.");
			}
		} else {
			System.out.println(postMethod.getStatusLine());
			try {
				response = postMethod.getResponseBodyAsString();
				System.out.println(response);
			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
		}
		return response;
	}
}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值