HttpURLConnection如何实现重定向、获取及设置cookie呢?
下文笔者讲述HttpURLConnection实现重定向,获取及设置Cookie的方法分享,如下所示
实现思路: HttpURLConnection在请求头中设置cookie的代码如下: conn.setRequestMethod("POST"); conn.setRequestProperty("Cookie", firstCookie);
HttpURLConnection获取重定向地址和cookie代码如下
public void first() throws Exception{ Map<String, String> paramsHashMap = new HashMap<String, String>(); paramsHashMap.put("testabc", "99999"); paramsHashMap.put("websitename", "java265"); 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); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。