【发布时间】:2014-01-14 03:09:13
【问题描述】:
我有点傻 - 对不起。
我编写了一个返回一些 JSON 的 API。我的目标是从 Android 应用程序中使用这个 API。我用 AsyncTask 尝试过,但失败了。
我想像这样使用它:
- 调用类,告诉 URL 和结果的类型。 (哪个json,比如账号信息或者一些数据)
- 加载完成后,调用结果的正确类,并将结果作为参数。
这里是 API 的链接:Link
我该怎么办?
编辑:
这是我的代码。他不喜欢GetRequest 变量类型,也不可能getHttpClientInstance。他也无法解析在 MyAsyncTask 上执行的方法。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) startActivity(new Intent(this, editPreference.class));
if (item.getItemId() == R.id.action_kurse) startActivity(new Intent(this, Login.class));
if (item.getItemId() == R.id.action_refresh) {
String url = "http://vplan.florian-schmidt.org/api/get_klassen.php";
new MyAsyncTask().execute(url);
};
return super.onOptionsItemSelected(item);
}
class MyAsyncTask extends AsyncTask <GetRequest,String,JSONObject> {
@Override
protected JSONObject doInBackground(GetRequest... params)
{
JSONObject data = null;
GetRequest eventRequest = params[0];
if (eventRequest instanceof GetRequest)
{
DefaultHttpClient httpClient = HttpClient.getHttpClientInstance();
try
{
HttpGet httpGet = HttpClient.getHttpGetInstance();
httpGet.setURI(eventRequest.getUriString());
httpGet.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpGet);
//Check is authentication to the server passed
if (httpResponse.getStatusLine().getStatusCode() == 401)
{
// do some actions to clear userID, token etc ...
// finish
finish();
}
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity instanceof HttpEntity)
data = new JSONObject(EntityUtils.toString(responseEntity));
responseEntity.consumeContent();
}
catch (ClientProtocolException CPException)
{
//set data to null, handle and log CPException
}
catch (IOException ioException)
{
//set data to null, handle and log IOException
}
catch (JSONException jsonException)
{
//set data to null, handle and log JSONException
}
catch (URISyntaxException useException)
{
//set data to null, handle and log URISyntaxException
}
}
return data;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(jsonObject.toString());
}
}
【问题讨论】:
标签: java android json api rest