HttpURLConnection获取重定向地址和cookie的代码如下:
public void first() throws Exception{ Map<String, String> paramsHashMap = new HashMap<String, String>(); paramsHashMap.put("IF_NO", "IF0002"); paramsHashMap.put("UID", "12345"); firstRequest(API_HTTP, paramsHashMap, "UTF-8"); } private void firstRequest(String path, Map<String, String> params, String encoding) throws Exception{ StringBuilder sb = new StringBuilder(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> 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<String,List<String>> map=conn.getHeaderFields(); Set<String> 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<String> 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);
时间: 2024-10-23 10:01:15