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

7y4bm7vi  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(365)

我想用字符串变量代替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字符串代替url,这意味着我想这样使用。

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

ip是一个字符串变量,在这个变量中我得到10.1.1.82
所以我怎么不能用这个?

q9yhzks0

q9yhzks01#

您也可以这样做:

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

biswetbf2#

只需连接字符串

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

相关问题