简体   繁体   中英

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:

 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? 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. Just use your actual URLs, don't try to out-think Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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