Java - sending HTTP parameters via POST method easily

前端 未结 17 2008
借酒劲吻你
借酒劲吻你 2020-11-21 05:54

I am successfully using this code to send HTTP requests with some parameters via GET method

void sendRequest(String request)
{
            


        
17条回答
  •  梦毁少年i
    2020-11-21 06:39

    In a GET request, the parameters are sent as part of the URL.

    In a POST request, the parameters are sent as a body of the request, after the headers.

    To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

    This code should get you started:

    String urlParameters  = "param1=a¶m2=b¶m3=c";
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;
    String request        = "http://example.com/index.php";
    URL    url            = new URL( request );
    HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
    conn.setDoOutput( true );
    conn.setInstanceFollowRedirects( false );
    conn.setRequestMethod( "POST" );
    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    conn.setRequestProperty( "charset", "utf-8");
    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    conn.setUseCaches( false );
    try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
       wr.write( postData );
    }
    

提交回复
热议问题