문제

Here is my curl request , which works perfectly fine.

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","value":"xxx.ipa"}]}'

Now I am trying to do this post from my java code using Httpconnection as shown below, but it gives me 400 bad request. Can the experts help me with this please.

    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();
도움이 되었습니까?

해결책

You missed the content type and json, check below:

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top