使用json发出HTTP post请求的问题

时间:2015-06-04 05:24:23

标签: java android rest http post

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

Error:Could not find any version that matches com.android.tools.build:gradle:1.2.3.+.
Searched in the following locations:
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/maven-metadata.xml
    file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/
    https://repo1.maven.org/maven2/com/android/tools/build/gradle/maven-metadata.xml
Required by:
    androidstudio-accelerometer-gps-master:WhenMoving:unspecified

请求发送到服务器,但没有使用我的JSON,所以我在我的响应中收到一条错误消息,说明我缺少必需的参数。

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

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;
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您尚未通过内容类型,因此服务器无法识别请求的类型...

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

befor setentity()

相关问题