在android的url中使用字符串变量代替ip地址?

时间:2017-09-05 06:19:40

标签: java android ip

我想在url调用中使用字符串变量代替ip地址。 我想在应用程序中使用ip地址和端口号登录。然后我想在共享首选项中保存此IP地址,然后在url调用中我想在共享首选项中使用该存储IP地址

我得到像这样的共享偏好的IP地址。

SharedPreferences pref = getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);


    ip= pref.getString("key_ip", null);           // getting Float

    Log.e("ip: ", "> " + ip);

然后我用这样的方法调用url。

public static String off33() {
        StringBuffer stringBuffer = new StringBuffer("");
        BufferedReader bufferedReader = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet();

            URI uri = new URI("http://10.1.1.82:80/outlet?3=ON");


            httpGet.setURI(uri);
            httpGet.addHeader(BasicScheme.authenticate(
                    new UsernamePasswordCredentials("admin", "kirti123"),
                    HTTP.UTF_8, false));

            HttpResponse httpResponse = httpClient.execute(httpGet);
            InputStream inputStream = httpResponse.getEntity().getContent();
            bufferedReader = new BufferedReader(new InputStreamReader(
                    inputStream));

            String readLine = bufferedReader.readLine();
            while (readLine != null) {
                stringBuffer.append(readLine);
                stringBuffer.append("\n");
                readLine = bufferedReader.readLine();
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    // TODO: handle exception
                }
            }
        }
        return stringBuffer.toString();
    }

所以,我想在方法10.1.1.82中使用ip string代替url意味着我想这样使用。

            URI uri = new URI("http://ip:80/outlet?3=ON");

ip是一个字符串变量,在这个变量中我得到10.1.1.82

所以我怎么不能用这个?

2 个答案:

答案 0 :(得分:1)

只需连接字符串

即可
URI uri = new URI("http://" + ip + ":80/outlet?3=ON");

答案 1 :(得分:0)

你也可以这样做:

String base = "http://%1$s:80/outlet?3=ON";
String address = String.format(base,ip);
URI uri = new URI(address);