2

I try to send a post request using a java program, I tested the post request URL in postman software, its working fine and post-operation are successful. But when I tried to replicate the same using java program with Http Url connection it pops out the 403 status as Forbidden.

Java code

public class Alexacreate {

public static void main(String Arg[]) throws MalformedURLException, IOException, JSONException {

    JSONObject productjson = new JSONObject();
    productjson.put("InternalID", "P987240");
    String input = productjson.toString();
    URL urlForUPdate = new URL("https://my348141.sapbydesign.com/sap/byd/odata/cust/v1/alexatest/MaterialCollection");
    HttpURLConnection conn = (HttpURLConnection) urlForUPdate.openConnection();
    conn.setRequestProperty("Authorization", "Basic RGV2VXNlcjAxOldlbGNvbWUwMQ==");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("x-csrf-token", "mQG3DNW_MMwaoIyvaqgepg==");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    System.out.println(input);
    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();
    conn.connect();
    System.out.println(conn.getResponseMessage());
    if (conn.getResponseCode() == 201) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String outPut;
        while ((outPut = bufferedReader.readLine()) != null) {

        }
        System.out.println("Created");
    } else {
        System.out.println("Not created");
    }
}

 }
S Mugunthan kumar
  • 177
  • 1
  • 2
  • 11
  • Possible duplicate of [403 Forbidden with Java but not web browser?](https://stackoverflow.com/questions/13670692/403-forbidden-with-java-but-not-web-browser) – Mohsen Aug 06 '19 at 13:01
  • 1
    Make a network trace of both requests and compare them in Wireshark to check the differences. – Jonaswg Aug 06 '19 at 13:02
  • It might be that you are using a HttpURLConnection to connect to a https link? I'd check out [HttpsURLConnection](https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/HttpsURLConnection.html) – Avi Aug 06 '19 at 13:13
  • No, still the same issue occurs when I changed to HttpsURLConnection – S Mugunthan kumar Aug 06 '19 at 13:20
  • can you check the Authorization header value is valid? – Voodoo Aug 06 '19 at 13:57
  • The authorization header value is valid – S Mugunthan kumar Aug 06 '19 at 15:28
  • There is a pre-flight request which goes before the actual rest call. I hope that is getting authenticated which should not be, because pre-flight calls do not carry the authorization header. – Nish Aug 14 '19 at 08:08

0 Answers0