简体   繁体   English

Android REST API连接

[英]Android REST API connection

I'm a little bit to stupid - sry for that. 我有点愚蠢 - 为此吵架。

I wrote an API which gives some JSON back. 我写了一个API,它给了一些JSON。 My goal is to use this API from an Android App. 我的目标是从Android应用程序中使用此API。 I've tried it with AsyncTask but failed hard. 我已经尝试过使用AsyncTask但是很难。

I imagine to use it like this: 我想像这样使用它:

  • Calling the class, telling the URL and the type of the result. 调用类,告诉URL和结果的类型。 (which json, like the account information or some data) (哪个json,像帐户信息或一些数据)
  • When the loading is finished, calling the right class of the result, with the result as argument. 加载完成后,调用结果的右侧类,并将结果作为参数。

Here's the link to the API: Link 这是API的链接: 链接

What do I have to do? 我需要做什么?

EDIT: 编辑:

Here's my code now. 这是我现在的代码。 He doesn't like the GetRequest variable type, also getHttpClientInstance is not possible. 他不喜欢GetRequest变量类型,也不能使用getHttpClientInstance。 He also cannot resolve the method execute on MyAsyncTask. 他也无法解决MyAsyncTask上的execute方法。

@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 :) 不要傻,每个人都必须从学习的地方开始:)

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. 正如Bosko所提到的,AsyncTask可能是最好的解决方案,因为你需要从主线程中取出任何I / O类型的操作,否则应用程序将崩溃。

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());
        }
    }

}

The onCreate sets an onClickListener onto a button, when the button is pressed a new AsyncTask is created and execute() is called. 所述onCreate设置一个onClickListener到按钮,当按钮被按下一个新的AsyncTask创建和execute()被调用。

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. doInBackground在一个单独的线程上运行,因此您可以在此处执行长时间运行的任务,例如调用REST API和处理响应。 See Boskos' answer for that bit of code. 请参阅Boskos对该代码的回答。

The onPostExecute happens after the task is complete, so you can handle your JSON object here and update the UI as you need to. onPostExecute在任务完成后发生,因此您可以在此处理JSON对象并根据需要更新UI。

If you haven't already done so, I'd highly suggest reading the AsyncTask docs . 如果您还没有这样做,我强烈建议您阅读AsyncTask 文档

Hope this helps 希望这可以帮助

In many application I used AsyncTask to communicate with API and IMO AsyncTask approach have a lot benefits. 在许多应用程序中,我使用AsyncTask与API进行通信,而IMO AsyncTask方法有很多好处。
Here is example of AsyncTask which gets the JSON data over the API: 以下是通过API获取JSON数据的AsyncTask示例:

private class EventsAsyncTask 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;
        }
    }

You have to post your code and point to problem, then SO users can help you. 您必须发布您的代码并指出问题,然后SO用户可以帮助您。 Everything else is personally opinion based and it is not constructive. 其他一切都是以个人意见为基础的,而且不具有建设性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM