HttpURLConnection重定向,获取及设置cookie

HttpURLConnection获取重定向地址和cookie的代码如下:
public  void first() throws Exception{
		Map paramsHashMap = new HashMap();
		paramsHashMap.put("IF_NO", "IF0002");
		paramsHashMap.put("UID", "12345");
		firstRequest(API_HTTP, paramsHashMap, "UTF-8");
	}

   private  void firstRequest(String path, Map params, String encoding) throws Exception{		
		StringBuilder sb = new StringBuilder();
		if(params!=null && !params.isEmpty()){
			for(Map.Entry entry : params.entrySet()){
				sb.append(entry.getKey()).append('=');
				sb.append(URLEncoder.encode(entry.getValue(), encoding));
				sb.append('&');
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		byte[] entity = sb.toString().getBytes();
		HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
		conn.setInstanceFollowRedirects(true);
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		OutputStream outStream = conn.getOutputStream();
		outStream.write(entity);
		//获取重定向地址
		redictURL= conn.getHeaderField( "Location" );

		System.out.println("第一次请求重定向地址 location="+redictURL);
		System.out.println("第一次请求 conn.getResponseCode()="+conn.getResponseCode());
		
		//获取cookie
		Map> map=conn.getHeaderFields();
		Set set=map.keySet();
		for (Iterator iterator = set.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			if (key.equals("Set-Cookie")) {
				System.out.println("key=" + key+",开始获取cookie");
				List list = map.get(key);
				StringBuilder builder = new StringBuilder();
				for (String str : list) {
					builder.append(str).toString();
				}
				firstCookie=builder.toString();
				System.out.println("第一次得到的cookie="+firstCookie);
			}
		}
		
	}


HttpURLConnection在请求头中设置cookie的代码如下:

 

conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", firstCookie);

你可能感兴趣的:(Android核心)