2016-09-13 46 views
1

我已經搜索並測試了2天每個我找到的代碼,絕對沒有運氣。 我正在發送一個json文件到一個servlet,並且我非常肯定數據是正確發送的;出於某種原因,我無法從請求的輸入流中獲取它們。發送JSON數據到servlet結果爲空字符串

這裏從數據發送方的代碼:

{ 
... 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("User-Agent", "Mozilla/5.0"); 
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
    con.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 

    Gson gson = new Gson(); 
    String jsonString = gson.toJson(<POJO_to_send>).toString(); 
    wr.writeBytes(URLEncoder.encode(jsonString,"UTF-8")); 

    wr.flush(); 
    wr.close();   

    String responseMessage = con.getResponseMessage(); 
... 
} 

從servlet代碼:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    String s = ""; 
    StringBuilder sb = new StringBuilder(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 

    while((s=br.readLine())!=null) { 
     s = br.readLine(); 
     sb.append(s); 
    } 

    String jsonString = sb.toString(); 
    if (jsonString != null) { 
     jsonString = br.readLine(); 
    }else{ 
     IOException ioex = new IOException("Error reading data."); 
     throw(ioex); 
    } 
} 

出於某種原因,我還沒有找到,sb.toString()導致空值,因爲sb是一個空字符串。從調試中我發現請求的輸入流的buf值似乎不是空的(至少有一些字節數據在它裏面,在我看來它們和發送者的數據輸出寫者是一樣的)。

您是否看到我錯過的一些錯誤?我可以在數據發送到servlet之前檢查數據嗎(也許編碼失敗了)?

任何建議/想法?

謝謝

+1

你在哪裏發送數據?我看不到寫。 – stdunbar

+0

應該是wr.writeBytes(URLEncoder.encode(jsonString,「UTF-8」)),如果我沒有錯的話。 –

+0

是什麼讓你認爲一個換行符在寫完之後奇蹟般地附加到了你的JSON字符串中? –

回答

0

你作爲stdunbar說,沒有寫入的OutputStream。謝謝joop-eggen的所有建議。

嘗試發送以下內容:

{ 
    ... 
     Gson gson = new Gson(); 
     DataOutputStream wr = new DataOutputStream(resp.getOutputStream()); 
     String jsonString = gson.toJson(<POJO_to_send>).toString(); 

     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
     conn.setRequestProperty("Content-Length", String.valueOf(jsonString.length())); 
     con.setDoOutput(true); 

     wr.writeBytes(jsonString); 
     wr.flush(); 
     wr.close();  

     String responseMessage = con.getResponseMessage(); 
    ... 
    } 

並獲得:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8")); 
    String sb = new String(); 
      try { 
      String line = ""; 
      while ((line = br.readLine()) != null) 
      sb += line; 
      } catch (Exception e) { 
      e.printStackTrace(); 
      } 

     String jsonString = sb; 
} 
+0

哦,對,現在的答案更好;) – Fr333du

+0

已編輯。你使用'doPost(...)'而不是'doGet(...)'嗎?你還檢查了'String jsonString = gson.toJson()。toString();'後'jsonString的值是多少? – Fr333du

+0

@RealSkeptic實際上這使我困惑了一下:因爲我設置了使用POST的請求方法,所以我期待着一個doPost執行服務器端,但是請求會通過doGet。 –

0

一個DataOutputStream類是contraproductive。如果沒有傳遞內容類型和字符集,代碼將變爲:

對於POST,預計會有一個HTML表單參數,如json=...。 不幸的是發佈表單數據需要更多格式化,所以讓我們一起嘗試一下。

HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
con.setRequestMethod("POST"); 
con.setRequestProperty("User-Agent", "Mozilla/5.0"); 
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
con.setDoOutput(true); 
con.connect(); // ............. 
OutputStream out = con.getOutputStream(); 

Gson gson = new Gson(); 
String jsonString = gson.toJson(<POJO_to_send>).toString() + "\r\n"; 
out.write(jsonString.getBytes(StandardCharsets.UTF_8)); 
out.close(); 

String responseMessage = con.getResponseMessage(); 

在每種情況下爲請求方法POST一個必須在servlet使用doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    BufferedReader br = new BufferedReader(
     new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8)); 

    StringBuilder sb = new StringBuilder(); 
    String s; 
    while ((s = br.readLine()) != null) { 
     sb.append(s).append("\n"); 
    } 

    String jsonString = sb.toString(); 
} 
+0

我同意你的看法,但似乎con.setRequestMethod(「POST」 )不起作用,並且請求以GET方式發送;還有以後的每一位製片人打來的電話似乎都不起作用,我真的不明白爲什麼。 –

+1

感謝您的評論。被遺忘的是'connect()'。我已經添加了它。這確實發送參數,標題並開始真正的連接。 'openConnection ... connect'是人們通常不會忘記的東西。 –

0

你必須更新屬性在server.xml中maxpostSize="",如果你使用的是Tomcat或相關屬性爲其他服務器