android json data to spring mvc4

430 Views Asked by At

I am new to using Spring mvc4 annotation . In all i want to do is using spring mvc as a web service . so i would be thankful if anyone could provide me a solution for it.

My android code is as:

HttpParams httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);
        HttpClient httpclient = new DefaultHttpClient(httpParams);
        HttpPost httppost = new HttpPost( "http://localhost:8080/datarequest");
        JSONObject json = new JSONObject();


            json.put("action", "check_login");
            json.put("username","name");
            json.put("password", "password");


        JSONArray postjson = new JSONArray();
        postjson.put(json);

        httppost.setHeader("json", json.toString());
        httppost.getParams().setParameter("jsonpost", postjson);

        System.out.println(postjson);
        HttpResponse response = httpclient.execute(httppost);

so far i wrote the web service as:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("/datarequest")
public class HelloController {

@RequestMapping(method = RequestMethod.GET)
public String getMethod(ModelMap model) {
    System.out.println("GET");

    return "hello";
}
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public String getMethod(ModelMap model) {
    System.out.println("POST");
    System.out.println("here i want to print json data send from the android ");


    return "hello";
}

}

1

There are 1 best solutions below

2
On BEST ANSWER

You can use @RequestBody and map it to required class structure. You can refer this SO question @RequestBody and @ReponseBody spring.

To test, you can map it to String. See below example.

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestHeader;

@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String getMethod(@RequestHeader(value="json") String headerStr) {
    System.out.println("POST");
    System.out.println(s);
    return "hello";
}

You can add below maven entry in your pom.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.1</version>
</dependency>