发布请求Java HTTP连接403禁止错误

时间:2019-08-06 12:59:40

标签: java json httpconnection

我尝试使用Java程序发送邮寄请求,我在邮递员软件中测试了邮寄请求URL,其工作正常且邮寄操作成功。但是,当我尝试使用带有Http Url连接的Java程序复制相同的内容时,它弹出403状态为“禁止访问”。

Java代码

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

 }

0 个答案:

没有答案