ApacheClient模拟浏览器GET和POST请求

LunaZhang 2011-11-11

ApacheClient简介HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.1.

模拟GET请求

HttpClient client = new DefaultHttpClient();
			//get..........get the login page
			String getUrl = "http://124.130.149.167:8888/nroa";
			HttpGet get = new HttpGet(getUrl);
			//execute get connection
			HttpResponse response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//request success
				String strResult = EntityUtils.toString(response.getEntity());
			}else{
				System.out.println("Error code:"
						+response.getStatusLine().getStatusCode());
			}

模拟post请求
//post...post the username and password to login
			String postUrl = "http://124.130.149.167:8888/nroa/checkLogin.do";
			HttpPost post = new HttpPost(postUrl);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair username = new BasicNameValuePair("USER_ID","test");
			NameValuePair password = new BasicNameValuePair("PASSWORD","1111");
			params.add(username);
			params.add(password);
			HttpEntity entity = new UrlEncodedFormEntity(params,"GBK");
			post.setEntity(entity);
			response = client.execute(post);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//request success
				String strResult = EntityUtils.toString(response.getEntity());
			}else{
				System.out.println("Error code:"
						+response.getStatusLine().getStatusCode());
			}

 常见问题:

1.post后由于页面发生跳转(比如由login.do跳转到main.jsp)

由于技术限制,以及为保证2.0发布版API的稳定,HttpClient还不能自动处重定向,但对重定向到同一主机、同一端口且采用同一协议的情况HttpClient可以支持。不能自动的处理的情况,包括需要人工交互的情况,或超出httpclient的能力。

当服务器重定向指令指到不同的主机时,HttpClient只是简单地将重定向状态码作为应答状态。所有的300到399(包含两端)的返回码,都表示是重定向应答。常见的有:

1.301永久移动.HttpStatus.SC_MOVED_PERMANENTLY

2.302临时移动.HttpStatus.SC_MOVED_TEMPORARILY

3.303SeeOther.HttpStatus.SC_SEE_OTHER

4. 307 临时重定向. HttpStatus.SC_TEMPORARY_REDIRECT

解决方案:在请求提交后再执行一次请求(如向login.do提交post请求后,再发送一次到main.jsp的get请求),代码如下:

if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//request success
				String strResult = EntityUtils.toString(response.getEntity());
			}if(response.getStatusLine().getStatusCode()==HttpStatus.SC_MOVED_TEMPORARILY){
				//login success,redirected,get the target url
				post.abort();//release the post connection 这句很重要
				String turl = response.getLastHeader("Location").getValue();
				//get to the main page after logining...
				get = new HttpGet(turl);
				response = client.execute(get);
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
}
}

相关推荐

yyzhu / 0评论 2015-11-01