Curl工作但相应的HttpConnection POST请求失败,因为400错误

时间:2014-01-29 10:22:47

标签: java rest post curl httpconnection

这是我的卷曲请求,完全正常。

curl -X POST http://build-master-mobile.xxx.com:8080/job/Reprovision-IPA/build --data-urlencode json ='{“parameter”:[{“name”:“IPA_URL”,“value”:“xxx”},{“name”:“ IPA_FILENAME”, “值”: “xxx.ipa”}]}“

现在我正在尝试使用Httpconnection从我的java代码中执行此帖子,如下所示,但它给了我400个错误请求。 请专家帮帮我。

    URL url = new URL("http://build-master-mobile.xxx.com:8080/job/Reprovision-IPA/build"); 
    URLConnection urlConnection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
    httpConn.setRequestProperty("Accept", "application/json");
    httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    httpConn.setRequestProperty("Connection", "keep-alive");
    httpConn.setRequestMethod("POST");

    String data = "{\"parameter\":[{\"name\":\"IPA_URL\",\"value\":\"xxx\"},{\"name\":\"IPA_FILENAME\",\"value\":\"xxx.ipa\"}]}";

    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    // send request

        OutputStreamWriter wr = new OutputStreamWriter(httpConn.getOutputStream());
        wr.write(data.toString());
        wr.flush();
        wr.close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    rd.close();

1 个答案:

答案 0 :(得分:1)

您错过了内容类型和json,请查看以下内容:

URL url = new URL("http://build-master-mobile.xxx.com:8080/job/Reprovision-IPA/build"); 
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Connection", "keep-alive");
httpConn.setRequestMethod("POST");

String data = "json='{\"parameter\":[{\"name\":\"IPA_URL\",\"value\":\"a\"},{\"name\":\"IPA_FI‌​LENAME\",\"value\":\"a.ipa\"}]}'";

httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// send request

    OutputStreamWriter wr = new OutputStreamWriter(httpConn.getOutputStream());
    wr.write(data.toString());
    wr.flush();
    wr.close();

BufferedReader rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
while ((line = rd.readLine()) != null) {
    result.append(line);
}
rd.close();