java-http communication

The java project uses HTTP requests. There are two main ways:
Use the HttpURLConnection method under the java.net package that comes with the JDK.

②Use apache's HttpClient method.

 

1. Use the HttpURLConnection method under the java.net package that comes with the JDK.

Method summary
abstract  void disconnect()
          Indicates that the server is unlikely to have other requests in the near future.
 InputStream getErrorStream()
          If the connection fails but the server still sent useful data, an error stream is returned.
static boolean getFollowRedirects()
          Returns a booleanvalue .
 String getHeaderField(int n)
          Returns the value of the nth header field.
 long getHeaderFieldDate(String name, long Default)
          Returns the value of the specified field parsed as a date.
 String getHeaderFieldKey(int n)
          Returns the key of the nth header field.
 boolean getInstanceFollowRedirects()
HttpURLConnectionReturns           instanceFollowRedirectsthe value of the field of this .
 Permission getPermission()
          Returns a permissions object representing the permissions required to establish the connection represented by this object.
 String getRequestMethod()
          Get request method.
 int getResponseCode()
          Get the status code from the HTTP response message.
 String getResponseMessage()
          Get the HTTP response message, if any, returned with the response code from the server.
 void setChunkedStreamingMode(int chunklen)
This method is used to enable streaming of HTTP request bodies without internal buffering when the content length is not known           in advance .
 void setFixedLengthStreamingMode(int contentLength)
          This method is used to enable streaming of HTTP request bodies without internal buffering when the content length is known in advance.
static void setFollowRedirects(boolean set)
          Sets whether this class should automatically perform HTTP redirects (requests with response code 3xx).
 void setInstanceFollowRedirects(boolean followRedirects)
          Sets whether this HttpURLConnectioninstance should automatically perform HTTP redirects (requests with response code 3xx).
 void setRequestMethod(String method)
          Set the method for the URL request, GET POST HEAD OPTIONS PUT DELETE TRACE One of the above methods is legal, depending on the restrictions of the protocol.
abstract  boolean usingProxy()
          Indicates whether the connection goes through a proxy.

sender:

public void requestFunction(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding( "utf-8"); // Set the encoding method of the request   
            response.setContentType("text/html;charset=utf-8"); // Set the encoding method when returning   
            String http = "" ;
            URL url = new URL(http); // Set the URL address of the HTTP connection 
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); // Generate the HttpURLConnection connection 
            httpURLConnection.setConnectTimeout(5000); // Set the connection timeout value 
            httpURLConnection.setRequestMethod ("post"); // Set the request method 
            httpURLConnection.setDoOutput( true ); // Allow output 
            httpURLConnection.setDoInput( true ); // Allow input 
            httpURLConnection.setUseCaches( false ); // Do not allow caching
            OutputStream outs = httpURLConnection.getOutputStream();
            OutputStreamWriter sWriter = new OutputStreamWriter(outs,"UTF-8"); // Set the output stream 
            sWriter.write(message); // Write the buffer stream 
            sWriter.flush(); // Flush the buffer stream 
            sWriter.close(); // Close the output stream 
            outs.close();
             int responseCode = httpURLConnection.getResponseCode(); // Get the returned request code
             // Indicates that the request is successful 
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream iStream = httpURLConnection.getInputStream(); // Get the output stream of the server, get the return data
                 // Read text from the character input stream, buffer each character, so as to achieve efficient reading of characters, arrays and lines. 
                BufferedReader bReader = new BufferedReader( new InputStreamReader(iStream));
                String len;
                String str = "";
                while ((len=bReader.readLine()) != null) {
                    str + = only;
                }
            }
        } catch (Exception e) {
        }
    }

Server:

private void responseFunction(HttpServletRequest request, HttpServletResponse response) {
        request.setCharacterEncoding("utf-8");  
        response.setContentType("text/html;charset=utf-8");  
        String str =request.getParameter("xxx"); // Get the parameters for sending HTTP request    
        response.getWriter().write("{\"message\":\"success\"}"); // Send to HTTP party returns response data   
    }

 

Guess you like

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