我正在尝试使用 Java 在 Azure 中添加虚拟机,我想知道是否有办法显示完整的错误消息,而不仅仅是状态代码和错误名称?
我使用 HttpsURLConnection
类中的 getResponseCode()
和 getResponseMessage()
。例如,我有 400
和 Bad request
但还不够详细。
编辑:这是我的 Java 代码
URL url = new URL("https://management.core.windows.net/myID/services/hostedservices/myHostedService/deployments");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.addRequestProperty("x-ms-version", "2014-05-01");
con.setRequestProperty("Content-Type", "application/xml");
InputStream errorStream = con.getErrorStream();//Get the error stream
if (errorStream != null) {//Read the detailed error message from the stream
String detailedErrorMessage = getStringFromInputStream(errorStream);
System.out.println(detailedErrorMessage);
}
最佳答案
并没有真正用 Java 进行工作(因此可能有更好的方法),但我在撰写同一主题的博客文章时确实遇到了类似的问题。这就是我找到错误详细信息的方法:
假设 con
是您的 HttpsURLConnection
对象:
int responseCode = con.getResponseCode();
InputStream errorStream = con.getErrorStream();//Get the error stream
if (errorStream != null) {//Read the detailed error message from the stream
String detailedErrorMessage = getStringFromInputStream(errorStream);
System.out.println(detailedErrorMessage);
}
这是 getStringFromInputStream
方法的实现:
// Source - http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
这是我编写的通用 post 方法:
private static int processPostRequest(URL url, byte[] data, String contentType, String keyStore, String keyStorePassword) throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException, ProtocolException {
SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
HttpsURLConnection con = null;
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslFactory);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("x-ms-version", "2013-08-01");
con.setRequestProperty("Content-Length", String.valueOf(data.length));
con.setRequestProperty("Content-Type", contentType);
DataOutputStream requestStream = new DataOutputStream (con.getOutputStream());
requestStream.write(data);
requestStream.flush();
requestStream.close();
int responseCode = con.getResponseCode();
InputStream errorStream = con.getErrorStream();
if (errorStream != null) {
String detailedErrorMessage = getStringFromInputStream(errorStream);
System.out.println(detailedErrorMessage);
}
return responseCode;
}
关于java - 使用 Java 中的 REST API Azure 获取详细的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23651977/