如何将Android应用程序连接到静态IP地址

时间:2013-02-05 15:11:05

标签: android wifi ip-address connect

我正在尝试开发一个需要通过wifi连接到另一台设备的应用。我知道其他设备的IP地址,但是当我尝试连接到它时,我无法做到。

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

1 个答案:

答案 0 :(得分:0)

您还需要指定这些:

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

因此,试试这个:

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