【发布时间】:2013-06-06 22:19:04
【问题描述】:
问题
我正在考虑将现有的 http post 方法转换为 spring-android,但我失败了。
JSONObject defaultJsonObject = new JSONObject();
defaultJsonObject.put("ln", "Kiat");
defaultJsonObject.put("CountryName", "Malaysia");
defaultJsonObject.put("CityName", "Kuala Lumpur");
这是我现有的 http 帖子,它正在运行,并将形成一个帖子正文:[json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}]
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", jsonObject.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
System.out.println("post param: " + postParams.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
但是当我使用 RestTemplate 转换为 Spring-android 时,它失败了。即使我已经设法将帖子正文形成为[json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}],但我不断收到 500 Internal Server Error
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
List<NameValuePair> postParams1 = new ArrayList<NameValuePair>();
postParams1.add(new BasicNameValuePair("json", jsonObject.toString()));
HttpEntity<?> requestEntity = new HttpEntity<Object>(postParams1, requestHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,String.class)
帖子正文格式将是这样的
[json={"ln":"Kiat","CountryName":"Malaysia","CityName":"Kuala Lumpur"}]
【问题讨论】:
-
收到 500 响应意味着服务器由于某些内部错误而崩溃。你能挖到那些吗?可能是您发送了一些错误数据,但如果没有服务器崩溃的详细信息,就很难知道问题出在哪里。
-
这是服务器端错误消息:值不能为空。参数名称:System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)处的输入
-
您发送的内容似乎无效...
-
问题已解决。是因为转换器的问题。我会用我的解决方案更新我的帖子。
标签: android json spring http-post resttemplate