【发布时间】:2016-03-20 21:03:04
【问题描述】:
我正在向需要基本身份验证的服务器发送 HttpsURLConnection 请求。我已经提供了授权值并对其进行了验证。但我收到了Http status 500: Internal Server error。这是我的代码:
public String httptest(String url, File f, String username, String password) throws Exception {
// Task attachments endpoint
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
// Set basic auth header
String apiKey = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(apiKey.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
logger.info("basicAuth: " + basicAuth);
// Indicate a POST request
connection.setDoOutput(true);
// A unique boundary to use for the multipart/form-data
String boundary = Long.toHexString(System.currentTimeMillis());
String fboundary = "----WebKitFormBoundary" + boundary + "u0gW";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + fboundary);
// Construct the body of the request
logger.info("boundary: " + fboundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
String fileName = f.getName();
String ffname = fileName.substring(fileName.lastIndexOf("\\")+1);
writer.append("--" + fboundary).append(LINE_FEED);
writer.append("Content-Disposition: multipart/form-data; name=\"file\"; filename=\"" + ffname + "\"").append(LINE_FEED);
writer.append("Content-Type: application/x-zip-compressed").append(LINE_FEED);
writer.append(LINE_FEED);
logger.info("fileName: " + fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
for (String line; (line = reader.readLine()) != null; ) {
writer.append(line).append(LINE_FEED);
}
} finally {
if (reader != null) try {
reader.close();
} catch (IOException logOrIgnore) {
}
}
writer.append(LINE_FEED);
writer.append("----" + fboundary).append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
writer.close();
} catch (Exception e) {
System.out.append("Exception writing file" + e);
} finally {
if (writer != null) writer.close();
}
logger.info("ResponseCode: " + connection.getResponseCode());
//System.out.println(connection.getResponseCode()); // Should be 200
return connection.getResponseMessage();
}
当我通过邮递员客户端发送相同的请求时,它工作正常。以下是邮递员请求的标头:
授权:基本 c2dveWFsQHF1YXJrLmNvbTpRdWFyazEyMw== 缓存控制:无缓存邮递员令牌: d6fac5f0-e844-9bac-2bce-51580fdd5557 内容类型: 多部分/表单数据;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW
----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data;名称=“文件”;文件名="Tiger522.zip" 内容类型: 应用程序/x-zip-压缩
----WebKitFormBoundary7MA4YWxkTrZu0gW
请告诉我该怎么做?
【问题讨论】:
-
发布服务器的堆栈跟踪
-
您没有发送相同的 Content-disposition:
Content-Disposition: multipart/form-data在您的代码中,Content-Disposition: form-data在邮递员客户端/ -
你可以看看这个。 stackoverflow.com/questions/1378920/….