Java HttpURLConnection 400错误

时间:2015-10-13 21:24:35

标签: jsp curl httpurlconnection

我正在尝试使用JSP设置类似CURL的请求,并且遇到400错误并且不确定问题是什么。我已阅读并且似乎无法弄清楚此代码有什么问题:

BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String inputLine;
String urlStr = "https://www.example.com/v1/Enroll/123456";
String key = "someusername0123456";
String qStr = "score=90&pass_fail=false&status=Completed";
String encodedKey = encoder.encodeBuffer(key.getBytes());
encodedKey = encodedKey.replaceAll("\n", ""); 
byte[] postData = qStr.getBytes("UTF-8");
URL url = new URL(urlStr);

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Basic "+encodedKey);
con.setRequestMethod("PUT");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
con.setRequestProperty("charset", "utf-8");
con.setDoOutput(true);
con.setInstanceFollowRedirects(false);
con.getOutputStream().write(postData);

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    while ((inputLine = reader.readLine()) != null) {
        out.println(inputLine);
    }
    reader.close();
} catch (Exception e) {}

响应代码为400,响应消息为Bad Request。我已经尝试了上面代码的许多变体,但没有任何效果。我无法控制发送到的服务器,但此CURL命令有效:

curl -X PUT https://www.example.com/v1/Enroll/123456 -u someusername0123456: -d "score=90" -d "pass_fail=false" -d "status=Completed"

0 个答案:

没有答案