2015-11-06 54 views
2

我想通過HttpUrlConnection發佈一個json請求(請注意,我只需要將數據推送到服務器,響應將被忽略)。我已經通過了幾個例子,但仍然無法實現它,沒有數據被添加到服務器。HttpUrlConnection請求不工作,沒有讀取響應

這裏是我的代碼:

URL url = new URL(urlString); 
    connection = (HttpURLConnection) url.openConnection(); 
    connection.setRequestMethod("POST"); 
    connection.setDoOutput(true); 
    connection.setRequestProperty("Content-Type", "application/json"); 
    connection.setRequestProperty("Accept", "application/json"); 

    OutputStream stream = connection.getOutputStream(); 
    stream.write(requestJSON.toString().getBytes()); 
    stream.flush(); 
    stream.close(); 

更新

我注意到代碼的工作,當我嘗試stream.close()後讀取響應,如:

connection.getResponseMessage() 

那是手段有必要閱讀響應以完成請求?

+1

之前的'stream.close()''添加connection.connect(); ' – user155542

+0

使用如下示例'OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream,「utf-8」)); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close();' – BNK

回答

1

使用本

如果請求是GET

public static String getDataUsingGetRequest(String urlVal) { 
    String Content = null; 
    BufferedReader reader = null; 
    try { 
     URL url = new URL(urlVal); 
     HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
     conn.setConnectTimeout(15 * 1000); 
     reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream())); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      sb.append(line); 
     } 

     Content = sb.toString(); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } finally { 
     try { 
      reader.close(); 
     } catch (Exception ex) { 
     } 
    } 
    return Content; 
} 

//如果請求是交

public static String getDataUsingPostRequest(String urlStr, String inputJson) { 

    String result = null; 
    try{ 
     URL url = new URL(urlStr); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Accept", "application/json"); 
     conn.setRequestProperty("Content-type", "application/json"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 
     conn.connect(); 
     OutputStream os = conn.getOutputStream(); 
     BufferedWriter writer = new BufferedWriter(
       new OutputStreamWriter(os, "UTF-8")); 
     writer.write(inputJson); 
     writer.flush(); 
     writer.close(); 
     os.close(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream())); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 

     while ((line = reader.readLine()) != null) { 
      sb.append(line); 
     } 
     result = sb.toString(); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
    return result; 
}