通过post请求获得服务端返回的数据
之前做项目的时候遇到的问题,现已解决,上传上来留个记录方便以后回顾。
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.OutputStream; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 7 public static String post(String json, String url) { 8 String line = null; 9 try { 10 URL url1 = new URL(url); 11 HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); 12 conn.setDoOutput(true); 13 conn.setDoInput(true); 14 // 设置不用缓存 15 conn.setUseCaches(false); 16 // 设置传递方式 17 conn.setRequestMethod("POST"); 18 // 设置维持长连接 19 conn.setRequestProperty("Connection", "Keep-Alive"); 20 // 设置文件字符集: 21 conn.setRequestProperty("Charset", "UTF-8"); 22 // 转换为字节数组 23 byte[] data = (json.getBytes()); 24 // 设置文件长度 25 conn.setRequestProperty("Content-Length", String.valueOf(data.length)); 26 // 设置文件类型: 27 conn.setRequestProperty("Content-Type", "application/json"); 28 // 开始连接请求 29 conn.connect(); 30 OutputStream out = conn.getOutputStream(); 31 // 写入请求的字符串 32 out.write(json.getBytes()); 33 out.flush(); 34 out.close(); 35 // 请求返回的状态 36 if (conn.getResponseCode() == 200) { 37 // 请求返回的数据 38 BufferedReader in = null; 39 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 40 line = in.readLine(); 41 } 42 } catch (Exception e) { 43 } 44 return line; 45 }