简体   繁体   English

使用带有URLConnection的Get请求

[英]using Get request with URLConnection

I am currently writing program to communicate with a device in my network, and the following code is what I have so far, it passed authentication and can get the webpage from the device, however i couldnt get the GET request to work, when I run the code below, i get the error: 我目前正在编写程序以与网络中的设备进行通信,到目前为止,以下代码是我通过的代码,它已通过身份验证并且可以从设备获取网页,但是当我运行时,我无法获得GET请求下面的代码,我得到错误:

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

when I input data on the webpage, its equivalent of going http://l192.168.xxx.xxx/2?A=3&p=1&X=1234 , and from tcpflow, it does GET /2?A=4&p=1&X=1234 HTTP/1.1 , I tried creating a new url connection with http://192.168.xxx.xxx/2?A=3&p=1&X=1234 , and it worked, but i have multiple input options and i dont want to create a new connection for each of them, how can I do the equivalent while staying connected? 当我在网页上输入数据时,相当于进入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连接,并且它起作用了,但是我有多个输入选项,并且我不想创建一个他们每个人都有新的连接,如何在保持连接状态的同时进行等效操作? or what I did wrong in the code? 还是我在代码中做错了什么?

thanks in advance. 提前致谢。

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();
}

I don't want to create a new connection for each of them 我不想为他们每个人创建一个新的连接

Don't worry about that. 不用担心 HttpURLConnection does connection pooling under the hood. HttpURLConnectionHttpURLConnection连接池。 Just use your actual URLs, don't try to out-think Java. 仅使用实际的URL,不要试图超越Java。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM