2012-01-10 155 views
1

我正在尋找教程或快速的例子,我怎麼可以發送POST數據扔openStream。如何通過url.openStream()發送POST數據?

我的代碼是:

URL url = new URL("http://localhost:8080/test"); 
      InputStream response = url.openStream(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8")); 

你能幫助我嗎?

+0

可能重複[發送HTTP POST請求在Java](http://stackoverflow.com/questions/3324717/sending-http-post- request-in-java) – 2012-01-10 14:10:00

回答

5
URL url = new URL(urlSpec); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod(method); 
    connection.setDoOutput(true); 
    connection.setDoInput(true); 

    // important: get output stream before input stream 
    OutputStream out = connection.getOutputStream(); 
    out.write(content); 
    out.close();   

      // now you can get input stream and read. 
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
    String line = null; 

    while ((line = reader.readLine()) != null) { 
     writer.println(line); 
    } 
+1

+1用於回答問題而不是跳轉到另一個庫。 – Dev 2012-01-10 14:41:45