Domanda

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();
È stato utile?

Soluzione

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();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top