简体   繁体   中英

How to connect Android app to an static ip address

I am trying to develop an app which needs to connect to another device via wifi. I know the IP address of the other device, however when I try to connect to it, I am not able.

private static String getUrl(String direccion) throws ConnectException{

    try {
        URL u = new URL("http://192.168.1.216");

        HttpURLConnection co = (HttpURLConnection) u.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(co.getInputStream()));
        String line;

        while ((line = reader.readLine()) != null) 
            //buffer.append(line);
            System.out.println(line);

         reader.close();
         co.disconnect();
         System.out.println("######InputStream CORRECTA... "+u);

         return line;
    } catch (MalformedURLException e) {
        throw new ConnectException();

    } catch (java.net.ConnectException e){
        throw e;

    } catch (IOException e) {
        throw new ConnectException();
    } 
}

You need to specify these also:

      co.setRequestMethod("GET");
      co.setDoOutput(true);
      co.connect();

Hence, try this :

private static String getUrl(String direccion) throws ConnectException {
    try {
        URL u = new URL("http://192.168.1.216");

        HttpURLConnection co = (HttpURLConnection) u.openConnection();
        co.setRequestMethod("GET");
        co.setDoOutput(true);
        co.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(co.getInputStream()));
        String line;

        while ((line = reader.readLine()) != null) 
            //buffer.append(line);
            System.out.println(line);

            reader.close();
            co.disconnect();
            System.out.println("######InputStream CORRECTA... "+u);

            return line;
    } catch (MalformedURLException e) {
        throw new ConnectException();

    } catch (java.net.ConnectException e){
        throw e;

    } catch (IOException e) {
        throw new ConnectException();
    } 
}

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