标签:
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 return result ; 35 }
/** * 根据URL地址和参数,获取返回数据 */ private String searchData_postMethod(String url, String jsonParam) throws IOException { URL postUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setRequestProperty("Cookie", responseCookie); // 设置login时返回的cookie connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/json"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(jsonParam); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); // 获取请求返回结果 String result = ""; String line; while ((line = reader.readLine()) != null) { result += line; } reader.close(); connection.disconnect(); return result ; }
标签:
原文地址:http://www.cnblogs.com/zj0208/p/5726952.html