httpclient 中post请求重定向

背景:使用httpclient 的post请求进行登录,需要重定向登录,请求重定向后的地址

在httpclient中post请求不像get请求自己可以重定向,实现方式是 判断post请求返回码是否是302,如果是那么就获取传递过来的Location的地址,进行拼接,在进行一个get的请求

实现代码

public Map<String, String> doPost(String url, Map<String, String> map, String charset) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		String domain = "http://user.hqygou.com";
		Map<String, String> returnmap = new HashMap<String, String>();
		try {
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
				System.out.println("请求的参数为:" + elem.getKey() + ":" + elem.getValue());
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			// 设置头部信息
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			HttpResponse response = httpClient.execute(httpPost);

			if (response != null) {
				int code = response.getStatusLine().getStatusCode();
				System.out.println("返回的code为:" + code);
				if (code == 302) {  #判断post的请求返回码
					Header[] hr = response.getAllHeaders();
					for (int i = 0; i < hr.length; i++) {
						Header header1 = hr[i];
						System.out.println("头部的所有内容:" + header1);
					}
					String hearder = response.getHeaders("Location")[0].toString().split(":")[1].trim(); #获取返回码中头部中location 就是重定向的地址
					String redirecturl = domain + hearder;  //需要和域名进行拼接
					System.out.println("开始重定向,地址为:" + redirecturl);
					cookies = response.getHeaders("Set-Cookie")[0].toString().split(":")[1].trim();
					System.out.println("获取的cookie:" + cookies);
					cookies = cookies.split(";")[0].trim();
					httpGet(redirecturl, cookies);  #get请求,把获取的cookie进行一个拼接
				} else {
					HttpEntity resEntity = response.getEntity();
					if (resEntity != null) {
						result = EntityUtils.toString(resEntity, charset);
					}
				}
				returnmap.put("content", result);
				returnmap.put("cookies", cookies);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return returnmap;
	}

  运行入口

	public static void main(String[] args) {
		test post = new test();
		String url = "http://xxx/login/index/checklogin";
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", "xx");
		map.put("username", "xx");
		map.put("password", "xx");
		post.doPost(url, map, "UTF-8");
	}

  

 注,后面这个200,是get请求时返回的内容,get请求可以查看另外一篇文章,http://www.cnblogs.com/chongyou/p/7808035.html 

转载于:https://www.cnblogs.com/chongyou/p/7807986.html

HttpClient 发送 POST 请求时,有可能会遇到服务器返回 302 的情况。这种情况通常是因为服务器需要进行重定向,而 HttpClient 默认是不会自动进行重定向的。 解决这个问题的方法,可以通过设置 HttpClient 的 RedirectStrategy 属性来实现自动重定向。下面是一个示例代码: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(60000) .setConnectTimeout(60000) .setRedirectsEnabled(true) // 允许自动重定向 .build(); httpPost.setConfig(requestConfig); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { // 处理正常情况的响应结果 } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) { // 处理重定向情况 String redirectUrl = httpResponse.getFirstHeader("Location").getValue(); // 重新发送请求,并处理响应结果 // ... } ``` 在上面的代码,我们通过设置 RequestConfig 的 setRedirectsEnabled(true) 来允许自动重定向。当服务器返回 302 状态码时,我们可以从响应头获取重定向的 URL,然后重新发送请求并处理响应结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值