android json 数据到 spring mvc4

android json data to spring mvc4

我刚开始使用 Spring mvc4 注释。总之,我想做的就是使用 spring mvc 作为 web 服务。所以如果有人能为我提供解决方案,我将不胜感激。

我的 android 代码如下:

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

到目前为止,我将 Web 服务编写为:

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

}

您可以使用 @RequestBody and map it to required class structure. You can refer this SO question @RequestBody and @ReponseBody spring.

要进行测试,您可以将其映射到字符串。请参阅下面的示例。

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

您可以在 pom 中添加以下 maven 条目。

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