【问题标题】:using Get request with URLConnection使用带有 URLConnection 的 Get 请求
【发布时间】:2013-02-21 22:41:46
【问题描述】:

我目前正在编写程序来与我的网络中的设备进行通信,以下代码是我目前所拥有的,它通过了身份验证并且可以从设备获取网页,但是我无法让 GET 请求工作,当我运行下面的代码时,我得到了错误:

 Exception in thread "main" java.io.FileNotFoundException: http://192.168.100.222:80
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)

当我在网页上输入数据时,它相当于去http://l192.168.xxx.xxx/2?A=3&p=1&X=1234,而从tcpflow,它是GET /2?A=4&p=1&X=1234 HTTP/1.1, 我尝试使用http://192.168.xxx.xxx/2?A=3&p=1&X=1234 创建一个新的 url 连接,它有效,但我有多个输入选项,我不想为每个输入选项创建一个新连接,我怎样才能在保持连接的同时做同样的事情?还是我在代码中做错了什么?

提前致谢。

public class main {
public static void main(String[] argv) throws Exception {
    Authenticator.setDefault(new MyAuthenticator());
    URL url = new URL("http://192.168.xxx.xxx");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write("Get /2?A=4&p=1&X=1234 HTTP1.1");
    out.close();        
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
            System.out.println(decodedString);
    }
    in.close();
}

【问题讨论】:

  • 它对我来说非常完美,没有任何问题。我尝试使用 localhost 而不是在网络中。我也没有使用Authenticator
  • 有什么你能想到的问题吗?
  • 删除Authenticator并检查
  • 设备需要身份验证,没有它,它根本无法连接也许我应该在out.write之前再做一个Authenticator

标签: java url networking network-programming ioexception


【解决方案1】:

我不想为他们每个人创建一个新的连接

别担心。 HttpURLConnection 在后台进行连接池。只需使用您的实际 URL,不要试图超越 Java。

【讨论】:

  • 有什么东西可以重新链接网址吗? url = http://192.168.xxx.xxx/2?A=3&p=1&X=1234 之类的东西?
  • @3v01 请用标准英语重述您的问题。我不知道你在说什么。
  • 有没有办法重新定义url中的url?
  • @3v01 我不知道你在说什么,但这没关系。 HTTP 连接池是在幕后自动为您完成的。您不必担心重用/重新定义任何东西。
猜你喜欢
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
相关资源
最近更新 更多