1. 程式人生 > >如何在HttpURLConnection設定Cookie

如何在HttpURLConnection設定Cookie

如何在HttpURLConnection設定Cookie:

 

  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 }