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;
	}
}


你可能感兴趣的:(java中利用httpClient的post方法请求远程接口)