0

我正在尝试将 json 对象发布到 .net Web 服务:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
answer[] answers = restTemplate.postForObject(url, new Gson().toJson(request), answer[].class);

到目前为止,生成的 json 看起来不错:

{"request":1234}

但是当在 restTemplate 的帮助下发送到 Web 服务时,http 请求的内容有点混乱:

"{\"request\":1234}"

并且服务以错误代码 400 bad request 响应

编辑:发现问题

问题是我对对象进行了两次编码。RestTemplate 已经将对象编码为 json。

工作代码是:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
answer[] answers = restTemplate.postForObject(url, request, answer[].class);
4

2 回答 2

1
use this method to post json over the server

public String postData(String url, JSONObject obj) {
        // Create a new HttpClient and Post Header
        String InsertTransactionResult = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 1000);
        HttpConnectionParams.setSoTimeout(myParams, 1000);

        try {

            HttpPost httppost = new HttpPost(url.toString());
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(obj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            Result = EntityUtils
                    .toString(response.getEntity());

        } catch (ClientProtocolException e) {

        } catch (IOException e) {
        }
        return Result;
    }
于 2012-06-05T08:07:18.670 回答
1

无需使用 gson 对对象进行编码,因为 RestTemplate 已经这样做了

正确的代码:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new GsonHttpMessageConverter());
answer[] answers = restTemplate.postForObject(url, request, answer[].class);
于 2012-06-05T18:40:43.307 回答