现在的位置: 首页 > 综合 > 正文

HttpClient 实现重定向 以表单方式post提交参数

2013年10月04日 ⁄ 综合 ⁄ 共 1068字 ⁄ 字号 评论关闭

先下载jar包:commons-httpclient-3.0.jar

主要部分代码如下:

 
                HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		String loginName = (String)request.getSession().getAttribute(Constants.SESSION_USER);
		
		// 填入各个表单域的值
		NameValuePair[] data = {
				new NameValuePair("name", "张三"),
				new NameValuePair("性别", "男"),
				};
		// 将表单的值放入postMethod中
		postMethod.setRequestBody(data);
		// 执行postMethod
		int statusCode = 0;
		try {
			statusCode = httpClient.executeMethod(postMethod);
			System.out.println("statusCode:" + statusCode);
			// 重定向
			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY
					|| statusCode == HttpStatus.SC_SEE_OTHER
					|| statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {

				// 从头中取出转向的地址
				Header locationHeader = postMethod.getResponseHeader("location");
				String location = null;
				if (locationHeader != null) {
					location = locationHeader.getValue();
					//System.out.println("The page was redirected to:" + location);
					response.sendRedirect(location);
				} else {
					System.err.println("Location field value is null.");
				}
				return;
			} else {
				String responseStr = postMethod.getResponseBodyAsString();
				System.out.println("responseStr:"+responseStr);
			}

抱歉!评论已关闭.