读取输入后无法写入输出 [英] Cannot write output after reading input

查看:1104
本文介绍了读取输入后无法写入输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 HttpURLConnection ,我正在编写一个连接到servlet的程序,但是在检查URL时卡住了

I'm writing a program that connects to a servlet thanks to a HttpURLConnection but I stuck while checking the 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"); 

}*/

我收到错误:


java.net.ProtocolException:读取输入后无法写入输出。

java.net.ProtocolException: Cannot write output after reading input.

如果我用注释中的代码检查网址,但它没有它完美地工作
不幸的是,我需要检查网址,所以我认为问题来自 getResponseCode 方法,但我不知道如何解决它

if i check the url with the code in comments but it work perfectly without it unfortunately, I need to check the url so i think the problem comes from the getResponseCode method but i don t know how to resolve it

非常感谢

推荐答案

HTTP协议基于请求 - 响应模式:您首先发送请求,服务器响应。一旦服务器响应,您就无法再发送任何内容,这是没有意义的。 (服务器如何在之前为您提供响应代码它知道您要发送的是什么?)

The HTTP protocol is based on a request-response pattern: you send your request first and the server responds. Once the server responded, you can't send any more content, it wouldn't make sense. (How could the server give you a response code before it knows what is it you're trying to send?)

所以当你打电话 server.getResponseCode(),您有效地告诉服务器您的请求已完成并且可以处理它。如果你想发送更多数据,你必须开始一个新请求。

So when you call server.getResponseCode(), you effectively tell the server that your request has finished and it can process it. If you want to send more data, you have to start a new request.

查看你的代码,你想检查连接本身是否成功,但是没有必要为此:如果连接不成功, server.connect()将抛出 Exception 。但是连接尝试的结果与HTTP响应代码不同,后者总是在服务器处理完所有输入后发生。

Looking at your code you want to check whether the connection itself was successful, but there's no need for that: if the connection isn't successful, an Exception is thrown by server.connect(). But the outcome of a connection attempt isn't the same as the HTTP response code, which always comes after the server processed all your input.

这篇关于读取输入后无法写入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆