我正在尝试访问本地主机中的 .php 文件:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.err.println("It's working ok?");
String url = "http://192.168.0.112/hlsystems/api/fetch.php";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
String query = "";
try {
query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
System.err.println(response.read());
Toast.makeText(mainContext, response.read(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(mainContext, e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
当我运行它时,出现以下错误:
W/System.err: android.content.res.Resources$NotFoundException: String resource ID #0x22
如果我从外部源/网络服务器检索字符串,我应该如何在 XML 文件中定义该字符串?
完整日志:
W/System.err: 123
W/ResourceType: No package identifier when getting value for resource number 0x00000022
W/System.err: android.content.res.Resources$NotFoundException: String resource ID #0x22
W/System.err: at android.content.res.Resources.getText(Resources.java:250)
W/System.err: at android.widget.Toast.makeText(Toast.java:268)
W/System.err: at com.hlsystems.ericsonwillians.saltodepirapora.MainActivity$2.run(MainActivity.java:89)
W/System.err: at java.lang.Thread.run(Thread.java:841)
最佳答案
response.read()
返回一个 int,即响应的单个字节。
在 Toast 之前,您需要将流响应转换为完整的字符串。
makeText 方法已重载,接受 R.string
资源 ID 作为第二个参数,这些资源是只读资源,无法在运行时创建
如果您只关心那一个字节,请参阅
关于java - 如何从外部源创建字符串资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49622267/