【发布时间】:2016-07-21 21:06:57
【问题描述】:
我已经实现了一个 Android 应用,到目前为止还没有遇到任何问题。
但是让一个异步 GET 请求工作大约花了我 3 天的时间,仍然没有进展。
我尝试使用 Android 文档并编写了一些代码.. 没有结果 然后我尝试了几乎所有在线解决方案..再次没有结果
能否请您提供针对 Android API 级别 21 中的异步 GET 请求的解决方案?
getRequest task = new getRequest();
String contents = null;
try {
contents = task.execute(url).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
这是我的课
public static class getRequest extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("headerFieldName", "I took out the fields here since they were personal");
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
result += (char) data;
data = reader.read();
}
return result;
} catch(Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
我也尝试使用 org.apache,但该库已从 API 级别 23 中删除。
谢谢!
【问题讨论】:
-
请贴一些代码!让我们看看您到目前为止拥有什么,我们会更轻松地为您提供帮助。
-
@TodorKostov 刚刚添加了代码,谢谢!
标签: java android asynchronous httprequest