gpt4 book ai didi

java - android json数据到spring mvc4

转载 作者:行者123 更新时间:2023-12-01 11:26:10 24 4
gpt4 key购买 nike

我刚开始使用 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);

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

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并将其映射到所需的类结构。你可以引用这个SO问题@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";
}

您可以在下面添加maven在你的 pom 中输入。

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

关于java - android json数据到spring mvc4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30797132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com