如何在play框架1.2.5中处理json请求

时间:2013-03-18 21:44:36

标签: android playframework httprequest playframework-1.x

我需要使用json数据参数从android appplay framework 1.2.5网络服务发送请求。我可以通过发送普通参数作为关键值来做到这一点。但我想将这些参数作为json对象发送。我不知道如何在routes和控制器静态函数中定义url来处理play framework 1.2.5中的json请求。

public ConnectService(String sngUrl,String searchkey,Double longitude,Double latitude,Double radius){
    try {
        jsonObject.put("searchkey", searchkey);
        jsonObject.put("longitude", longitude); 
        jsonObject.put("latitude", latitude);
        jsonObject.put("radius", radius);
    } catch (JSONException e) {
        System.out.println("HATA 1 : "+e.getMessage());
        e.printStackTrace();
    }

    jArrayParam = new JSONArray();
    jArrayParam.put(jsonObject); 

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
    nameValuePair.add(new BasicNameValuePair("jsonRequest", jsonObject.toString()));
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(sngUrl);
    httppost.addHeader("Content-Type", "application/json");         
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8" ));//HTTP.UTF_8   
        System.out.println("URLLLLLLLL : "+httppost.getRequestLine());
        response = httpclient.execute(httppost);                 
        entity = response.getEntity();

    } catch (UnsupportedEncodingException e) {
        System.out.println("HATA 2 : "+e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        System.out.println("HATA 3 : "+e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("HATA 4 : "+e.getMessage());
        e.printStackTrace();
    }
    finally{

    }

}

这是我的路线和控制器方法

POST     /search                                       Application.search(jsonRequest)

//not for json request
public static void searchproduct(String searchkey,Double longitude,Double latitude,Double radius){
    String d=searchkey+" "+longitude+" "+latitude+" "+radius ;
    renderJSON(d);
}

1 个答案:

答案 0 :(得分:0)

我认为您在Play应用中声明路由和操作时出错了。

来自Android应用的HTTP响应有一个名为jsonRequest的查询参数。因此,您在Play应用中的操作也应该被接受一个名为jsonRequest的查询参数。因此,在您的Play应用中,解决方案可能如下:

路线

# Associate to searchproduct action method
POST     /search        Application.searchproduct

控制器

//not for json request
public static void searchproduct(String jsonRequest) {
    // convert string to JSON object using org.json.JSONObject
    org.json.JSONObject jsonObject = new org.json.JSONObject(jsonRequest);

    // get all the json element
    String searchkey = jsonObject.getString("searchkey")
    Double radius = jsonObject.getDouble("radius")
    ...... // get the rest element

    // here maybe the rest of logic such as, construct JSON and render
    ......
}

This post可能对您有用。