背景:使用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