服务器端JSP代码,用于从请求中提取/检索JSON对象

时间:2014-10-01 14:11:40

标签: android json jsp client-server httpclient

如何检索我使用HTTPClient POST方法发送到我的服务器的JSON对象。我想在JSP页面中检索服务器上的这个JSON对象。我google了很多,但要么没有答案,要么全部都是PHP。

以下是我用来向我的服务器发送数据的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
}

1 个答案:

答案 0 :(得分: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) {
    }
}