Http

private String httpPost(final String url, final Map parms)
			throws IOException
	{

		String body = null;
		// 构造HttpClient的实例
		final HttpClient httpClient = new HttpClient();
		// 创建POST方法
		final PostMethod postMethod = new PostMethod(url);
		// 传参数
		final NameValuePair[] data = new   NameValuePair[parms.keySet().size()];
		final Iterator it = parms.entrySet().iterator();
		int i = 0;
		// 循环取出MAP参数中的值
		while (it.hasNext())
		{
			final Map.Entry entry = (Map.Entry) it.next();
			final Object key = entry.getKey();
			final Object value = entry.getValue();
			data[i] = new NameValuePair(key.toString(), value.toString());
			i++;
		}
		// 将参数的值放入postMethod中
		postMethod.setRequestBody(data);
		// 状态码
		int statusCode;
		try
		{
			statusCode = httpClient.executeMethod(postMethod);
			// 获取回传内容
			body = postMethod.getResponseBodyAsString();
		}
		finally
		{
			// 释放连接
			postMethod.releaseConnection();
		}
		Header[] aa;
		// 根据状态值,看是否跳转
		PostMethod redirect = null;
		if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
				|| statusCode == HttpStatus.SC_MOVED_PERMANENTLY
				|| statusCode == HttpStatus.SC_SEE_OTHER
				|| statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)
		{
			// 读取新的URL地址
			Header header = postMethod.getResponseHeader("location");
			aa = postMethod.getResponseHeaders();
			if (header != null)
			{
				String newuri = header.getValue();
				if (newuri == null || newuri.equals(""))
				{
					newuri = "/";
				}
				redirect = new PostMethod(newuri);

				try
				{
					statusCode = httpClient.executeMethod(redirect);
					// 如果请求当前页面没有值,在获取跳转后页面的值
					if (null == body || "".endsWith(body))
					{
						body = redirect.getResponseBodyAsString();
						aa = redirect.getResponseHeaders();
					}
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					redirect.releaseConnection();
				}
			}
		}
		return body;
	}

你可能感兴趣的:(http)