如何在HttpURLConnection设置Cookie(Finn_ZengYuan博客)
如何在HttpURLConnection设置Cookie:
主要是
conn.setRequestProperty("Cookie", "data");
其中的“cookie”需要和服务器端设置的“Cookie”保持一致(key保持一致)
1 /****** 2 * Created by Finn on 2018/11/26. 3 * Author Finn 4 */ 5 6 public class ConnHttp { 7 public static final String DEF_CHATSET = "UTF-8"; 8 public static final int DEF_CONN_TIMEOUT = 30000; 9 public static final int DEF_READ_TIMEOUT = 30000; 10 11 public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36"; 12 13 public static String COOKIE = ""; 14 15 //申请KEY 16 public static final String APPKEY ="869662030640897"; 17 //申请页数 18 public static final int APPYE = 1; 19 20 //1.事件列表 21 public static String getRequest1(Context context, int tepy){ 22 23 String result = null; 24 // "http://113.107.244.182:3303/Home/Pub/getHistoryDeviceInfo?imei=869662030640897" 25 String url ="http://113.107.244.182:3303/Home/Pub/getHistoryDeviceInfo";//请求接口地址 26 Map params = new HashMap();//请求参数 27 if(tepy == 1){//.获得验证码http://113.107.244.182:3303/Home/Api/getValidateMessage 28 url ="http://113.107.244.182:3303/Home/Api/getValidateMessage"; 29 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDRegLock","")); 30 }else if(tepy == 2){//注册:http://113.107.244.182:3303/Home/Api/register 31 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDRegLock","")); 32 params.put("pswd",ToolsSharedPrefer.getStringSharedPreferences(context,"TDNBLockPsw","")); 33 params.put("code",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnCode","")); 34 35 url ="http://113.107.244.182:3303/Home/Api/register"; 36 }else if(tepy == 3){//登陆:http://113.107.244.182:3303/Home/Api/login 37 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnLock","")); 38 params.put("pswd",ToolsSharedPrefer.getStringSharedPreferences(context,"TDNBLockPsw","")); 39 url ="http://113.107.244.182:3303/Home/Api/login"; 40 }else if(tepy == 4){//找回密码http://113.107.244.182:3303/Home/Api/findpsw 41 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDRegLock","")); 42 params.put("code",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnCode","")); 43 params.put("npswd",ToolsSharedPrefer.getStringSharedPreferences(context,"TDNBNewPsw","")); 44 url ="http://113.107.244.182:3303/Home/Api/findpsw"; 45 }else if(tepy == 5){//修改密码http://113.107.244.182:3303/Home/Api/changepsw 46 params.put("uuid",ToolsSharedPrefer.getStringSharedPreferences(context,"TDuuidLock","")); 47 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnLock","")); 48 params.put("pswd",ToolsSharedPrefer.getStringSharedPreferences(context,"TDNBLockPriPsw","")); 49 params.put("npswd",ToolsSharedPrefer.getStringSharedPreferences(context,"TDNBNewPsw","")); 50 url ="http://113.107.244.182:3303/Home/Api/changepsw"; 51 }else if(tepy == 6){//退出登陆http://113.107.244.182:3303/Home/Api/loginout 52 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnLock","")); 53 url ="http://113.107.244.182:3303/Home/Api/loginout"; 54 }else if(tepy == 7){//.设备信息http://113.107.244.182:3303/Home/Api/deviceinfo 55 params.put("uuid",ToolsSharedPrefer.getStringSharedPreferences(context,"TDuuidLock","")); 56 params.put("imei",ToolsSharedPrefer.getStringSharedPreferences(context,"TDIMEILock","")); 57 params.put("username",ToolsSharedPrefer.getStringSharedPreferences(context,"TDFinnLock","")); 58 url ="http://113.107.244.182:3303/Home/Api/deviceinfo"; 59 } 60 try { 61 result = net(context,url, params, "GET",tepy); 62 ToolsLog.LogE("COOKIE==",COOKIE); 63 if(tepy == 1 && tepy == 2 && tepy == 3) { 64 ToolsSharedPrefer.setSharedPreferencesAll(context, "SETCOOKIE", COOKIE); 65 } 66 ToolsLog.LogE("返回结果",result); 67 // JSONObject object = JSONObject.parseObject(result); 68 // if(object.getInteger("state")== 0){ 69 // ToolsLog.LogE("GET请求成功",object.get("state")+""); 70 // }else{ 71 // System.out.println(object.get("error_code")+":"+object.get("reason")); 72 // } 73 } catch (Exception e) { 74 e.printStackTrace(); 75 }finally { 76 params.clear(); 77 } 78 return result; 79 } 80 81 /** 82 * @param strUrl 请求地址 83 * @param params 请求参数 84 * @param method 请求方法 85 * @return 网络请求字符串 86 * @throws Exception 87 */ 88 public static String net(Context context,String strUrl, Map params,String method,int cookie) throws Exception { 89 90 HttpURLConnection conn = null; 91 BufferedReader reader = null; 92 String rs = null; 93 String sessionid = ""; 94 95 try { 96 97 StringBuilder sb = new StringBuilder(); 98 if(method==null || method.equals("GET")){ 99 strUrl = strUrl+"?"+urlencode(params); 100 ToolsLog.LogE("GET请求数据",strUrl); 101 } 102 URL url = new URL(strUrl); 103 conn = (HttpURLConnection) url.openConnection(); 104 ToolsLog.LogE("------", 105 ToolsSharedPrefer.getStringSharedPreferences(context, "SETCOOKIE", "") 106 + "----" + sessionid); 107 if(!"".equals(ToolsSharedPrefer.getStringSharedPreferences(context,"SETCOOKIE",""))) { 108 conn.setRequestProperty("Cookie", ToolsSharedPrefer.getStringSharedPreferences(context, "SETCOOKIE", "")); 109 } 110 conn.setRequestProperty("User-agent", userAgent); 111 112 //sessionid值格式:JSESSIONID=AD5F5C9EEB16C71EC3725DBF209F6178,是键值对,不是单指值 113 if(method==null || method.equals("GET")){ 114 conn.setRequestMethod("GET"); 115 conn.setUseCaches(true); 116 }else{ 117 conn.setRequestMethod("POST"); 118 conn.setDoOutput(true); 119 } 120 121 // //设置允许输入 122 // conn.setDoInput(false); 123 124 //设置请求中的媒体类型信息。 125 // conn.setRequestProperty("Content-Type", "application/json"); 126 //设置客户端与服务连接类型 127 // conn.addRequestProperty("Connection", "Keep-Alive"); 128 129 conn.setConnectTimeout(DEF_CONN_TIMEOUT); 130 conn.setReadTimeout(DEF_READ_TIMEOUT); 131 conn.setInstanceFollowRedirects(false); 132 ToolsLog.LogE("connect","11111111111---------"+conn.getResponseCode()); 133 conn.connect(); 134 // 取得sessionid. 135 String cookieval = conn.getHeaderField("set-cookie"); 136 if(cookieval != null) { 137 sessionid = cookieval.substring(0, cookieval.indexOf(";")); 138 ToolsLog.LogE("cookieval",sessionid+"---------"+cookieval); 139 if(!sessionid.equals("")) { 140 COOKIE = sessionid; 141 } 142 } 143 144 145 if (params!= null && method.equals("POST")) { 146 try { 147 DataOutputStream out = new DataOutputStream(conn.getOutputStream()); 148 out.writeBytes(urlencode(params)); 149 } catch (Exception e) { 150 // TODO: handle exception 151 } 152 } 153 InputStream is = conn.getInputStream(); 154 reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); 155 String strRead = null; 156 while ((strRead = reader.readLine()) != null) { 157 sb.append(strRead); 158 } 159 rs = sb.toString(); 160 } catch (Exception e) { 161 e.printStackTrace(); 162 } finally { 163 if (reader != null) { 164 reader.close(); 165 } 166 if (conn != null) { 167 conn.disconnect(); 168 } 169 } 170 return rs; 171 } 172 173 //将map型转为请求参数型 174 public static String urlencode(Map<String,Object>data) { 175 StringBuilder sb = new StringBuilder(); 176 for (Map.Entry i : data.entrySet()) { 177 try { 178 sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&"); 179 } catch (UnsupportedEncodingException e) { 180 e.printStackTrace(); 181 } 182 } 183 ToolsLog.LogE("请求数据",sb.toString()); 184 return sb.toString(); 185 } 186 }
一个成功的人,会不但的学习,不但的提升自己!一个成功的程序猿也是如此!