Android REST API 连接 [英] Android REST API connection

查看:23
本文介绍了Android REST API 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点愚蠢 - 对此请原谅.

I'm a little bit to stupid - sry for that.

我编写了一个 API,它返回了一些 JSON.我的目标是从 Android 应用程序使用此 API.我已经用 AsyncTask 试过了,但失败了.

I wrote an API which gives some JSON back. My goal is to use this API from an Android App. I've tried it with AsyncTask but failed hard.

我想像这样使用它:

  • 调用类,告诉 URL 和结果的类型.(哪个json,比如账户信息或者一些数据)
  • 加载完成后,调用结果的正确类,并将结果作为参数.

这是 API 的链接:链接

Here's the link to the API: Link

我该怎么办?

这是我的代码.他不喜欢 GetRequest 变量类型,也无法使用 getHttpClientInstance.他也无法解析在 MyAsyncTask 上执行的方法.

Here's my code now. He doesn't like the GetRequest variable type, also getHttpClientInstance is not possible. He also cannot resolve the method execute on 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());
    }


}

推荐答案

我有点愚蠢 - 对此请原谅.

I'm a little bit to stupid - sry for that.

别傻了,每个人在学习时都必须从某个地方开始:)

Don't be silly, everyone has to start from somewhere when learning :)

正如 Bosko 所提到的,AsyncTask 可能是这里最好的解决方案,因为您需要从主线程中删除任何 I/O 类型的操作,否则应用程序将崩溃.

As Bosko mentions, an AsyncTask is probably the best solution here because you need to take any I/O type operations off the main thread, otherwise the application will crash.

我回答了一个类似的问题返回,但相同的代码适用,请参阅下面的内容.

I answered a similar question a while back, but the same code applies, please see the below.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.btn);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://date.jsontest.com";
                new MyAsyncTask().execute(url);
            }
        });


    }
    class MyAsyncTask extends AsyncTask<String,Void,JSONObject> {

        @Override
        protected JSONObject doInBackground(String... urls) {
            return RestService.doGet(urls[0]);
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            TextView tv = (TextView) findViewById(R.id.txtView);
            tv.setText(jsonObject.toString());
        }
    }

}

onCreate 在按钮上设置一个 onClickListener,当按钮被按下时,一个新的 AsyncTask 被创建并调用 execute().

The onCreate sets an onClickListener onto a button, when the button is pressed a new AsyncTask is created and execute() is called.

doInBackground 在单独的线程上运行,因此您可以在此处执行长时间运行的任务,例如调用 REST API 和处理响应.请参阅 Boskos 对那段代码的回答.

The doInBackground runs on a separate thread so you can perform long running tasks here, such as calling your REST API and handling the response. See Boskos' answer for that bit of code.

onPostExecute 在任务完成后发生,因此您可以在此处处理您的 JSON 对象并根据需要更新 UI.

The onPostExecute happens after the task is complete, so you can handle your JSON object here and update the UI as you need to.

如果您还没有这样做,我强烈建议您阅读 AsyncTask 文档.

If you haven't already done so, I'd highly suggest reading the AsyncTask docs.

希望能帮到你

这篇关于Android REST API 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆