请检查以下代码。代码的作用是使用firstHttpConn
检查响应代码并打开secondHttpConn
。如果响应代码为401,请将基本身份验证标头添加到secondHttpConn
。然后发布数据并阅读响应。
但是,代码会引发Cannot write output after reading input
错误。我检查了Stack Overflow上的其他问题,如this one,我确信我没有犯同样的错误。
//I hate using Java 6 and HttpURLConnection, but the code is for a very old system.
private static XmlObject callWebService(String soapMessage, String webServiceEndpoint, String soapAction) throws Exception {
XmlObject resultXMLObject;
HttpURLConnection firstHttpConn = null;
HttpURLConnection secondHttpConn = null;
try {
byte[] streamoutByteArray = soapMessage.getBytes("UTF-8");
URL url = new URL(webServiceEndpoint);
firstHttpConn = (HttpURLConnection) url.openConnection();
firstHttpConn.connect();
if (firstHttpConn.getResponseCode() == 401) {
firstHttpConn.disconnect();
secondHttpConn = (HttpURLConnection) url.openConnection();
secondHttpConn.setRequestProperty("Authorization", "Basic " + getBasicAuth());
} else {
firstHttpConn.disconnect();
secondHttpConn = (HttpURLConnection) url.openConnection();
}
secondHttpConn.setConnectTimeout(30000);
secondHttpConn.setReadTimeout(300000);
secondHttpConn.setRequestProperty("Content-Length", String.valueOf(streamoutByteArray.length));
secondHttpConn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8);
secondHttpConn.setRequestProperty("SOAPAction", soapAction);
secondHttpConn.setRequestMethod("POST");
secondHttpConn.setDoOutput(true);
secondHttpConn.setDoInput(true);
OutputStream out = secondHttpConn.getOutputStream();
out.write(streamoutByteArray);
out.close();
//Line 238 below.
InputStreamReader isr = new InputStreamReader(secondHttpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer sb = new StringBuffer();
while ((inputLine = in.readLine()) != null)
sb.append(inputLine).append("\n");
in.close();
resultXMLObject = XmlObject.Factory.parse(sb.toString());
} finally {
if (firstHttpConn != null)
firstHttpConn.disconnect();
if (secondHttpConn != null)
secondHttpConn.disconnect();
}
return resultXMLObject;
}
日志:
Caused By: java.net.ProtocolException: Cannot write output after reading input.
at weblogic.net.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:271)
at org.company.member.esb.webservice.WebServiceClient.callWebService(WebServiceClient.java:238)
at org.company.member.esb.webservice.WebServiceClient.invokeWebserviceV01(WebServiceClient.java:132)
at sun.reflect.GeneratedMethodAccessor711.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Truncated. see log file for complete stacktrace
任何人都知道为什么?感谢。
答案 0 :(得分:0)
您没有运行此处粘贴的代码。您可以看到这些行不匹配,因为堆栈跟踪中有HttpURLConnection.getOutputStream
,但您声明
//Line 238 below.
InputStreamReader isr = new InputStreamReader(secondHttpConn.getInputStream());
因此堆栈跟踪和粘贴的代码不同。
我没有看到您在此处粘贴的代码存在问题。