Obtain the data returned by the server through the post request

The problems encountered in the previous project have been solved, and they are uploaded to keep a record for future review.

 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              // set without caching 
15              conn.setUseCaches( false );
 16              // set delivery method 
17              conn.setRequestMethod("POST" );
 18              // set maintenance Long connection 
19              conn.setRequestProperty("Connection", "Keep-Alive" );
 20              // Set file character set: 
21              conn.setRequestProperty("Charset", "UTF-8" );
 22              // Convert to byte array 
23              byte [] data =(json.getBytes());
 24              // Set the file length 
25              conn.setRequestProperty("Content-Length" , String.valueOf(data.length));
 26              // Set the file type: 
27              conn.setRequestProperty("Content- Type", "application/json" );
 28              // Start the connection request 
29              conn.connect();
 30              OutputStream out = conn.getOutputStream();
 31              // Write the requested string 
32              out.write(json.getBytes ());
 33              out.flush();
 34              out.close();
 35              // The status returned by the request
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     }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324712557&siteId=291194637