2013-03-18 72 views
0

我需要發送請求jsonandroid appplay framework 1.2.5網絡服務的數據參數。我可以通過發送正常參數作爲關鍵值來做到這一點。但我想將這些參數作爲json對象發送。我不知道如何在routes和控制器靜態函數中定義url來處理play framework 1.2.5中的json請求。如何處理播放框架中的json請求1.2.5

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); 
} 

回答

0

我想你在遊戲應用程序宣告路線和行動有失誤。

來自Android應用程序的HTTP響應有一個名爲jsonRequest的查詢參數。因此,您在Play應用中的操作也應該被接受一個名爲jsonRequest的查詢參數。所以,在你玩的應用,該解決方案也許像以下:

路線

# 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也許對你有用的參考。

+0

感謝它的工作。我在我的httppost頭上也有一個錯誤。我應該像這樣httppost.addHeader(「Content-Type」,「application/x-www-form-urlencoded」); – demlik 2013-03-19 11:25:09