gpt4 book ai didi

java - 没有在 Spring Controller 方法中获取 JSON 值

转载 作者:行者123 更新时间:2023-11-29 22:06:37 25 4
gpt4 key购买 nike

我需要从我的 Android 设备向我的服务器发送一些数据。我正在通过 JSON 执行此操作。我已经在 Android 上实现了 JSON 帖子,并且我正在尝试在服务器端进行映射以检索该数据。我的问题是我一直得到一个空字符串。

用于发送JSON的Android方法:

private void sendJson(final String json, final String URL) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
try{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
client.execute(post);
}
catch(Exception e){
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}

服务器端方法:

@RequestMapping(value = "/getLatestCalls", method = RequestMethod.POST)
public void getData(@ModelAttribute String json){
//... do something
}

问题是,在这个方法中,我的 json 字符串每次都是“”。我也尝试过使用 @RequestParam 但它不再进入该方法。我也尝试过使用 @ModelAttribute("json")

有人可以在这里稍微启发一下吗?提前谢谢你。

最佳答案

这是解决方案,它工作正常。

服务器端

@Controller
public class DataCollector {

@RequestMapping(value = "/clientdatacollector", method = RequestMethod.POST)
public @ResponseBody
void abc(Writer writer, @RequestParam("gpsdata") String gpsJSON) {



try {
// here is your jsonstring ;)
writer.write(gpsJSON.toString());

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

}

}

客户端

 public static void httptest() {
ArrayList<TravellingData> tdArray = new ArrayList<TravellingData>();
Gson gson = new Gson();
String jsonString = "";
for (int i = 0; i < 1; i++) {
tdArray.add(ObjectCreater.createMockTravellingDataObject());
}

jsonString = gson.toJson(tdArray);

HttpClient client = new DefaultHttpClient();

HttpPost post = null;
try {
post = new HttpPost(
"http://localhost:8080/uygulama/clientdatacollector");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("gpsdata", jsonString));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = null;
try {
response = client.execute(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}

} catch (IOException e) {
e.printStackTrace();
}

}

关于java - 没有在 Spring Controller 方法中获取 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644598/

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