ulq*_*rra 14 java httpurlconnection
我正在编写一个连接到servlet的程序,感谢a HttpURLConnection但是我在查看url时卡住了
public void connect (String method) throws Exception {
server = (HttpURLConnection) url.openConnection ();
server.setDoInput (true);
server.setDoOutput (true);
server.setUseCaches (false);
server.setRequestMethod (method);
server.setRequestProperty ("Content-Type", "application / xml");
server.connect ();
/*if (server.getResponseCode () == 200)
{
System.out.println ("Connection OK at the url:" + url);
System.out.println ("------------------------------------------- ------- ");
}
else
System.out.println ("Connection failed");
}*/
Run Code Online (Sandbox Code Playgroud)
我收到了错误:
java.net.ProtocolException:读取输入后无法写入输出.
如果我用注释中的代码检查网址,但不幸的是它完美地工作,我需要检查网址,所以我认为问题来自getResponseCode方法,但我不知道如何解决它
非常感谢你
biz*_*lop 25
HTTP协议基于请求 - 响应模式:您首先发送请求,服务器响应.一旦服务器响应,您就无法发送更多内容,这是没有意义的.(在知道你要发送什么内容之前,服务器怎么能给你一个响应代码?)
所以当你打电话时server.getResponseCode(),你有效地告诉服务器你的请求已经完成并且它可以处理它.如果要发送更多数据,则必须启动新请求.
查看您的代码,您想要检查连接本身是否成功,但是没有必要:如果连接不成功,Exception则抛出一个server.connect().但是连接尝试的结果与HTTP响应代码不同,HTTP响应代码总是在服务器处理完所有输入之后.
我认为例外不是由于printing url.在读取响应之后,应该尝试编写一些代码来设置请求体.
如果您在获取HttpURLConnection.getOutputStream()后尝试获取,则会发生此异常HttpURLConnection.getInputStream()
这是sun.net.www.protocol.http.HttpURLConnection.getOutputStream的实现:
public synchronized OutputStream getOutputStream() throws IOException {
try {
if (!doOutput) {
throw new ProtocolException("cannot write to a URLConnection"
+ " if doOutput=false - call setDoOutput(true)");
}
if (method.equals("GET")) {
method = "POST"; // Backward compatibility
}
if (!"POST".equals(method) && !"PUT".equals(method) &&
"http".equals(url.getProtocol())) {
throw new ProtocolException("HTTP method " + method +
" doesn't support output");
}
// if there's already an input stream open, throw an exception
if (inputStream != null) {
throw new ProtocolException("Cannot write output after reading
input.");
}
if (!checkReuseConnection())
connect();
/* REMIND: This exists to fix the HttpsURLConnection subclass.
* Hotjava needs to run on JDK.FCS. Do proper fix in subclass
* for . and remove this.
*/
if (streaming() && strOutputStream == null) {
writeRequests();
}
ps = (PrintStream)http.getOutputStream();
if (streaming()) {
if (strOutputStream == null) {
if (fixedContentLength != -) {
strOutputStream =
new StreamingOutputStream (ps, fixedContentLength);
} else if (chunkLength != -) {
strOutputStream = new StreamingOutputStream(
new ChunkedOutputStream (ps, chunkLength), -);
}
}
return strOutputStream;
} else {
if (poster == null) {
poster = new PosterOutputStream();
}
return poster;
}
} catch (RuntimeException e) {
disconnectInternal();
throw e;
} catch (IOException e) {
disconnectInternal();
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37586 次 |
| 最近记录: |