请求不适用于HttpURLConnection,但适用于其他HTTP客户端

时间:2018-03-27 09:09:07

标签: java http post connection httpurlconnection

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://some.cz/url")
        .post(new FormBody.Builder().build())
        .addHeader("Jenkins-Crumb", "325asdfse534")
        .addHeader("Authorization", "Basic 5645762535t")
        .addHeader("Cache-Control", "no-cache")
        .addHeader("Postman-Token", "563b8065-87b0-47a4-b9af-eaaeaaab4bb0")
        .build();
System.out.println("response.code() = " + client.newCall(request).execute().code());

使用此代码,状态代码为200

HttpURLConnection connection = (HttpURLConnection)
        new URL("http://some.cz/url").openConnection();
connection.setRequestProperty("Jenkins-Crumb", "325asdfse534");
connection.setRequestProperty("Authorization", "Basic 5645762535t");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Postman-Token", "563b8065-87b0-47a4-b9af-eaaeaaab4bb0");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.getOutputStream().write(new byte[0]);
System.out.println("connection.getResponseCode() = " + connection.getResponseCode());

此处状态代码为403。有什么区别?

1 个答案:

答案 0 :(得分:0)

尝试添加

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");