1. 登录时保存cookie
1 private String responseCookie;
1 /** 2 * 根据URL地址和参数,获取返回数据 3 */ 4 private String login_postMethod(String url, String jsonParam) throws IOException { 5 URL postUrl = new URL(url); 6 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); 7 connection.setDoOutput(true); 8 connection.setDoInput(true); 9 connection.setRequestMethod("POST"); // 设置访问类型 10 connection.setUseCaches(false); 11 connection.setInstanceFollowRedirects(true); 12 connection.setRequestProperty("Content-Type", "application/json"); //设置参数类型 13 connection.setRequestProperty("Connection", "Keep-Alive"); 14 connection.connect(); 15 16 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 17 out.writeBytes(jsonParam); 18 out.flush(); 19 out.close(); 20 21 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));//设置返回数据编码 22 responseCookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie 23 24 // 获取请求返回结果 25 String result = ""; 26 String line; 27 while ((line = reader.readLine()) != null) { 28 result += line; 29 } 30 31 reader.close(); 32 connection.disconnect(); 33 34 logger.info("url : " + url); 35 logger.info(result); 36 37 return result; 38 }
2 .根据首次登录保存的cookie,再次访问webservice接口
1 /** 2 * 根据URL地址和参数,获取返回数据 3 */ 4 private String reconnnect_postMethod(String url, String jsonParam) throws IOException { 5 URL postUrl = new URL(url); 6 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); 7 connection.setRequestProperty("Cookie", responseCookie); // 设置login时返回的cookie 8 connection.setDoOutput(true); 9 connection.setDoInput(true); 10 connection.setRequestMethod("POST"); 11 connection.setUseCaches(false); 12 connection.setInstanceFollowRedirects(true); 13 connection.setRequestProperty("Content-Type", "application/json"); 14 connection.connect(); 15 16 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 17 out.writeBytes(jsonParam); 18 out.flush(); 19 out.close(); 20 21 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 22 23 // 获取请求返回结果 24 String result = ""; 25 String line; 26 while ((line = reader.readLine()) != null) { 27 result += line; 28 } 29 30 reader.close(); 31 connection.disconnect(); 32 33 return result; 34 }
时间: 2024-10-17 20:26:15