我已经看到如果之前调用了getInputStream会抛出此错误,但我没有在我的代码中并且我已经检查了connected属性为false,但仍然显示此错误。代码如下:
private void testConnect() throws Exception{
HttpURLConnection con = null;
OutputStream httpsend = null;
String url = "https://xxxxx/goldapi/rs/checkPaymentService";
TrustManager[] trustall = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustall, new SecureRandom());
HostnameVerifier allHostsValid = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
System.out.println("URL Host: " + hostname + " vs. " + session.getPeerHost());
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
con = (HttpsURLConnection)(new URL(url).openConnection());
con.setConnectTimeout(100000);
// Set HTTP parameters for SOAP call
//con.disconnect(); // test
con.setAllowUserInteraction(true);
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
byte[] b = "test".getBytes();
con.setRequestProperty( "Content-Length", String.valueOf( b.length));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
//Send request to server
httpsend = con.getOutputStream();
httpsend.write(b);
httpsend.flush();
try{
httpsend.close();
}catch(Exception e){
e.printStackTrace();
}
}
它将抛出异常
线程中的异常" main" java.net.ProtocolException:无法重置方法:
at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:320)
在sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:354)
在Test.PSGConnectTest.testConnect(PSGConnectTest.java:62)
在Test.PSGConnectTest.main(PSGConnectTest.java:24)
已经连接我发现我需要显式写
con.disconnect();
防止此错误,但运行
时抛出另一个奇怪的异常httpsend = con.getOutputStream();
此语句将抛出异常,如下所示
java.net.ProtocolException:读取输入后无法写入输出。
但是我没有读取任何输入(之前没有getInputStream),那么问题是什么?
更新: 我发现只有当我在eclipse中使用调试模式时才会出现此错误,如果在eclipse运行模式下运行则不会出现此错误。