0

Spring Controller

 @RequestMapping(value = "/login", produces="application/json;charset=UTF-8" ,method = RequestMethod.POST)
 @ResponseBody
 public int checkLoginInfo(@RequestParam Map<String, String> params) {
     User user=new Gson().fromJson((String) params.get("user"), User.class);
     return userService.getUserInfo(user);
 }   

HTML

var params={userid:$("#userid").val(),password:$("#password").val()}
$ajax({method:"post",data:{user:JSON.stringify(params)},url:"foo.bar"});

It worked on website. But I don't know how to send that Json object for android.

data:{user:JSON.stringify(params)}

I have tested

    private static String makeJsonMsg() {
    String retMsg = "";

    JSONStringer jsonStringer = new JSONStringer();

    try {


        retMsg = jsonStringer.object()
                    .key("user").object()
                        .key("userid").value("userid")
                        .key("password").value("1234")
                    .endObject()
                .endObject().toString();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return retMsg;

}

like that, But return 500 error. Do I need to add header or something else?

USER
  • 741
  • 4
  • 10
  • 21
  • Error 500 means that there was a server-side problem. You'll need to include the exception stack trace, the code without it isn't enough to diagnose the problem. – kryger Apr 04 '16 at 11:09

1 Answers1

0

The simple way, taken from @Sachin Gurnani's answer to How to send a JSON object over Request with Android?

public void postData(String url,JSONObject obj) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams );
    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/> json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

How to use

JSONObject requestObject = new JSONObject();
requestObject.put("userid", email);
requestObject.put("password", password);

postData("http://your/login/url",requestObject)
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Gueorgui Obregon
  • 5,077
  • 3
  • 33
  • 57