【问题标题】:Issue making HTTP post request with json使用 json 发出 HTTP 发布请求的问题
【发布时间】:2015-06-04 05:24:22
【问题描述】:

我的请求代码可以在这里看到:

public static void execute() {
    Map<String, String> comment = new HashMap<String, String>();
    comment.put("sourceCode", "int x = 0;");
    comment.put("language", "54");
    comment.put("input", "");
    String json = new GsonBuilder().create().toJson(comment, Map.class);
    HttpResponse response = makeRequest("http://api.compilers.sphere-engine.com/api/v3/submissions?access_token" +
            "=a3bdc6343aa21ebe9f28ecd7c8a8c43f", json);
    try {
        String responseStr = EntityUtils.toString(response.getEntity());
        Log.d("Response", responseStr);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public static HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        Log.d("ResponseLate", EntityUtils.toString(httpPost.getEntity()));
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

请求是向服务器发出的,但没有使用我的 JSON,因此我在响应中收到一条错误消息,指出我缺少必需的参数。

在 makeRequest 方法中,我记录 httpPost.getEntity() 并获取此值

06-04 01:21:45.814  24533-24736/me.dylanredfield.testbase3 D/ResponseLate﹕ {"input":"","language":"54","sourceCode":"int x \u003d 0;"}

感谢大家的帮助!

【问题讨论】:

  • 对于您的代码,我得到{"error":"WRONG_LANG_ID"} 我正在使用httpclient-4.3.3

标签: java android rest http post


【解决方案1】:

您还没有传递内容类型,因此服务器无法识别请求的类型...

设置

httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");

在 setentity() 之前

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多