HTTP url 连接 Android
HTTP url connection Android
我无法让我的应用程序打开到 URL 的连接,这是一个在线 JSON 文件。我遵循了如何让 inBackground 线程获取 URL 的指南,尽管当我在那个 URL 上调用 .connect() 时,它似乎 return 脱离了 inBackground 函数,因为我测试过只是有一个将被修改并显示为 Toast 的字符串,并且在 httpConn.connect() 之后立即修改字符串根本不会造成任何变化。我确保我的权限在清单中是正确的,但也许我忽略了一些小事。
protected String doInBackground(URL... urls){
InputStream in = null;
String result = "test";
int responseCode = -1;
try {
URL url = urls[0];
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
result = "get here";
httpConn.connect();
result = "don't get here";
responseCode = httpConn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
httpConn.disconnect();
result = readIt(in, 10);
return result;
}
catch (Throwable t){
t.printStackTrace();
}
return result;
}
关于导致没有任何联系的原因的任何想法或如何测试我是否只是忽略或不完全理解这一点?如果需要,我可以添加额外的代码。谢谢
据我了解,您想连接到 url 的 returns json 响应。我说得对吗?如果是,那么您需要访问 this link 以获得完整的解决方案。
我无法让我的应用程序打开到 URL 的连接,这是一个在线 JSON 文件。我遵循了如何让 inBackground 线程获取 URL 的指南,尽管当我在那个 URL 上调用 .connect() 时,它似乎 return 脱离了 inBackground 函数,因为我测试过只是有一个将被修改并显示为 Toast 的字符串,并且在 httpConn.connect() 之后立即修改字符串根本不会造成任何变化。我确保我的权限在清单中是正确的,但也许我忽略了一些小事。
protected String doInBackground(URL... urls){
InputStream in = null;
String result = "test";
int responseCode = -1;
try {
URL url = urls[0];
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
result = "get here";
httpConn.connect();
result = "don't get here";
responseCode = httpConn.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
httpConn.disconnect();
result = readIt(in, 10);
return result;
}
catch (Throwable t){
t.printStackTrace();
}
return result;
}
关于导致没有任何联系的原因的任何想法或如何测试我是否只是忽略或不完全理解这一点?如果需要,我可以添加额外的代码。谢谢
据我了解,您想连接到 url 的 returns json 响应。我说得对吗?如果是,那么您需要访问 this link 以获得完整的解决方案。