[英]URL connection HTTP POST connection refused
I am working on a Java desktop application with Java 7. For my application, I want to send data with POST to a server (using HTTP). 我正在使用Java 7开发Java桌面应用程序。对于我的应用程序,我想通过POST将数据发送到服务器(使用HTTP)。 The server is running on my local machine on localhost.
服务器正在本地主机上的本地计算机上运行。 But if I am trying to connect to the server, an connection reset (SocketTimeoutException) is returned.
但是,如果我尝试连接到服务器,则返回连接重置(SocketTimeoutException)。 I can`t connect, I have also tried to connect to a webpage like http://www.google.de , but it also fails.
我无法连接,我也尝试连接到http://www.google.de之类的网页,但也失败了。 The var body contains the POST data in correct form.
var主体包含正确格式的POST数据。 (I have also tried to connect with disabled firewall) My code:
(我也尝试连接禁用的防火墙)我的代码:
body=body.substring(0,body.length()-2);
HttpURLConnection connection = null;
try {
if (revision){ //Connect to the revision server
this.urlRevision = new URL(this.settingsRevision.getAddress());
connection = (HttpURLConnection) urlRevision.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(body);
writer.flush();
this.returnedData = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for(String line; (line = returnedData.readLine()) != null;){
System.out.println(line);
}
writer.close();
this.returnedData.close();
}
} catch (Exception e) {
this.exception=e;
}
You should try close the connection like this: 您应该尝试像这样关闭连接:
} finally {
if(connection != null) {
connection.disconnect();
}
}
I have already added it to the comments: 我已经将其添加到评论中:
System.setProperty("java.net.preferIPv4Stack" , "true");
Reason: Java is using IPv6 functions on my computer but IPv4 is used for internet connection (on my computer and by my provider (T-Online)). 原因:Java在我的计算机上使用IPv6功能,但IPv4用于Internet连接(在我的计算机上和我的提供者(T-Online))。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.