【问题标题】:Java: Preview HttpPost RequestJava:预览 HttpPost 请求
【发布时间】:2012-01-23 13:47:09
【问题描述】:

我正在尝试使用 Java 将 JSON 格式的数据发送到服务器。信息正在到达服务器,但服务器正在响应“错误请求”。

    HttpPost httpost = new HttpPost(path);

    StringEntity se = new StringEntity(JSONRequest);

    //sets the post request as the resulting string
    httpost.setEntity(se);

    //sets a request header so the page receving the request will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json;charset=utf8");
    HttpResponse response = httpclient.execute(httpost);

这是我请求的基本设置。这是 JSONData:

    {"clientApplicationDto":{"AuthenticationToken":"","BrandId":12,"MobileDeviceApplicationId":0},"mobileDeviceInfo":{"CarrierName":"MTN-SA","OsVersion":"2.2.2","ClientApplicationVersion":"TEST","DeviceManufacturer":"HTC","DeviceName":"HTC Desire","DeviceUniqueId":"1e9766fa2ef4c53a","OsName":"8","ClientApplicationTypeId":3}}

如果你觉得这很合适,我会开始向管理员发送垃圾邮件,但现在,我需要知道我是否遗漏了什么。

【问题讨论】:

  • Hm.. 对于初学者,StringEntity(或者更确切地说是任何AbstractHttpEntity 子类)有一个内容类型,默认情况下它将设置为常量HTTP.PLAIN_TEXT_TYPE,使用HTTP.DEFAULT_CONTENT_CHARSET 作为字符集。考虑通过调用se#setContentType("application/json;charset=utf-8") 来设置您的内容类型。顺便说一句,您的 JSON 看起来格式正确。
  • 只是为了检查帖子或 java 代码是否有问题,您是否尝试过类似 Chrome REST 控制台的请求? chrome.google.com/webstore/detail/…

标签: java android json


【解决方案1】:

我发现了问题...服务器对内容类型标头和内容格式非常敏感

    httpost.setHeader("Content-type", "application/json;charset=utf8");

需要改成

    httpost.setHeader("Content-type", "application/json; charset=utf-8");

和 StringEntity se = new StringEntity(JSONRequest);

需要改成

     StringEntity se = new StringEntity(JSONRequest,"utf-8");

感谢 Jens,一条评论将我推向了正确的方向。

【讨论】:

  • 很高兴知道它对你有帮助^_^
【解决方案2】:

试试这个,对你有好处

    private static String sendRequestPost(String url, Object obj) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpPost httpost = new HttpPost(url);
            if (obj != null) {
                httpost.setEntity(new StringEntity(new Gson().toJson(obj), "utf-8"));
                System.out.println("Request Json => " + new Gson().toJson(obj));
            }
            httpost.setHeader("Accept", "application/json");
            httpost.setHeader("Content-type", "application/json; charset=utf8");

            HttpResponse response = httpClient.execute(httpost);

            HttpEntity responseEntity = response.getEntity();
            String strResponse = EntityUtils.toString(responseEntity);
            return strResponse;
        }
        catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }

    }

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多