Java - sending HTTP parameters via POST method easily

前端 未结 17 1770
借酒劲吻你
借酒劲吻你 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条回答
  •  不思量自难忘°
    2020-11-21 06:40

    I couldn't get Alan's example to actually do the post, so I ended up with this:

    String urlParameters = "param1=a¶m2=b¶m3=c";
    URL url = new URL("http://example.com/index.php");
    URLConnection conn = url.openConnection();
    
    conn.setDoOutput(true);
    
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    
    writer.write(urlParameters);
    writer.flush();
    
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    writer.close();
    reader.close();         
    

提交回复
热议问题