2014-10-01 71 views
0

如何檢索使用HTTPClient POST方法向我的服務器發送的JSON對象。我想在我的JSP頁面的服務器上檢索這個JSON對象。我GOOGLE了很多,但無論是沒有答案或他們都是PHP。從請求中提取/檢索JSON對象的服務器端JSP代碼

以下是我用來向我的服務器發送數據的Github代碼。代碼僅適用於客戶端。我嘗試了很多不同的方法來在服務器端的JSP頁面中訪問這個JSON對象,但是我的所有嘗試都失敗了。此外,我對谷歌上可用的JSON庫的數量感到困惑。

JSONObject jsonobj= new JSONObject(); 
try { 
    // adding some keys 
    jsonobj.put("key", "value"); 
    jsonobj.put("weburl", "hashincludetechnology.com"); 

} catch (JSONException ex) { 
    // some code here 
} 
// Now lets begin with the server part 
try { 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppostreq = new HttpPost(wurl); 
    StringEntity se = new StringEntity(jsonobj.toString()); 
    //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
    se.setContentType("application/json;charset=UTF-8"); 
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8")); 
    httppostreq.setEntity(se); 
    HttpResponse httpresponse = httpclient.execute(httppostreq); 
    HttpEntity resultentity = httpresponse.getEntity(); 
    if(resultentity != null) { 
     // do other things 
    } 
}catch(Exception){ 
    // Log Exception 
} 

回答

0

我知道我太晚了,但我只是回答備案,希望這有助於

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    System.out.println("Post request recieved !!!"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); 
    String jsonParam = ""; 
    if (br != null) { 
     jsonParam = br.readLine(); 
    } 
    System.out.println(jsonParam); 
    JSONObject obj; 
    try { 
     obj = new JSONObject(jsonParam); 
     System.out.println(obj.get("username")); 
     System.out.println(obj.get("data")); 
    } catch (JSONException e) { 
    } 
} 
+0

雖然我已經實現了它沒有JSON,還是非常感謝您抽出寶貴時間來回答我題。這將有助於其他用戶。 – Kshitij 2015-02-12 10:19:52