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

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

问题描述

我是有点愚蠢 - SRY为

我写这给出了一些JSON回来的API。我的目标是使用这个API从Android应用。我已经与AsyncTask的尝试过,但失败的硬盘。

我想用这样的:


  • 调用类,告诉URL和结果的类型。 (这JSON,如帐户信息或某些数据)

  • 当加载完成后,调用正确的类的结果,其结果作为参数。<​​/ li>

下面是链接到API:链接

我有什么做的?

编辑:

下面是我的code现在。他不喜欢的GetRequest变量类型,也getHttpClientInstance是不可能的。他也无法解析方法上MyAsyncTask执行。

  @覆盖
公共布尔onOptionsItemSelected(菜单项项){
    如果(item.getItemId()== R.id.action_settings)startActivity(新意图(这一点,编辑preference.class));
    如果(item.getItemId()== R.id.action_kurse)startActivity(新意图(这一点,Login.class));
    如果(item.getItemId()== R.id.action_refresh){
        字符串URL =htt​​p://vplan.florian-schmidt.org/api/get_klassen.php;
        新MyAsyncTask()执行(URL);
    };
    返回super.onOptionsItemSelected(项目);
}类MyAsyncTask扩展的AsyncTask&LT;的GetRequest,字符串,JSONObject的&GT; {    @覆盖
    受保护的JSONObject doInBackground(...的GetRequest PARAMS)
    {
        JSONObject的数据= NULL;        的GetRequest eventRequest =参数[0];
        如果(eventRequest的instanceof的GetRequest)
        {
            DefaultHttpClient的HttpClient = HttpClient.getHttpClientInstance();            尝试
            {
                HTTPGET HTTPGET = HttpClient.getHttpGetInstance();
                httpGet.setURI(eventRequest.getUriString());                httpGet.setHeader(内容类型,应用/ JSON);                HTT presponse HTT presponse = httpClient.execute(HTTPGET);                //检查是身份验证通过服务器
                如果(HTT presponse.getStatusLine()的getStatus code()== 401)
                {
                    //做一些动作来清除用户ID,令牌等..
                    //完成
                    完();
                }                HttpEntity responseEntity = HTT presponse.getEntity();                如果(responseEntity的instanceof HttpEntity)
                    数据=新的JSONObject(EntityUtils.toString(responseEntity));                responseEntity.consumeContent();
            }
            赶上(ClientProtocolException CPException)
            {
                //组数据为null,处理和日志CPException
            }
            赶上(IOException异常IOException异常)
            {
                //组数据为null,处理和日志IOException异常
            }
            赶上(JSONException jsonException)
            {
                //组数据为null,处理和日志JSONException
            }
            赶上(的URISyntaxException useException)
            {
                //组数据为null,处理和记录的URISyntaxException
            }        }
        返回的数据;
    }    @覆盖
    保护无效onPostExecute(的JSONObject的JSONObject){
        TextView的电视=(的TextView)findViewById(R.id.textView);
        tv.setText(jsonObject.toString());
    }
}


解决方案

  

我是有点愚蠢 - SRY为


别傻了,每个人都有从什么地方开始学习时:)

由于博斯科提到,一个是AsyncTask的可能是最好的解决方案,在这里,因为你需要采取任何I / O操作型关闭主线程,否则应用程序会崩溃。

我回答了<一个href=\"http://stackoverflow.com/questions/20629227/unable-to-call-rest-api-in-android/20633685#20633685\">similar 的问题而回,但同样的code适用,请参见下面的。

 公共类MainActivity延伸活动{    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        Button按钮=(按钮)findViewById(R.id.btn);
        button.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                字符串URL =htt​​p://date.jsontest.com;
                新MyAsyncTask()执行(URL);
            }
        });
    }
    类MyAsyncTask扩展的AsyncTask&LT;弦乐,无效的JSONObject&GT; {        @覆盖
        受保护的JSONObject doInBackground(字符串的URL ...){
            返回RestService.doGet(网址[0]);
        }        @覆盖
        保护无效onPostExecute(的JSONObject的JSONObject){
            TextView的电视=(的TextView)findViewById(R.id.txtView);
            tv.setText(jsonObject.toString());
        }
    }}

的onCreate 设置一个 onClickListener 到一个按钮,当按钮为pressed一个新的AsyncTask是创建和的execute()被调用。

doInBackground 在一个单独的线程上运行,所以你可以在这里执行长时间运行的任务,如调用你的REST API和处理的响应。见Boskos'答案code的那一点。

onPostExecute 发生在任务完成后,这样你就可以在这里处理你的JSON对象,并更新用户界面,因为你需要。

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

希望这有助于

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

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.

I imagine to use it like this:

  • Calling the class, telling the URL and the type of the result. (which json, like the account information or some data)
  • 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

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. 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 :)

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

}

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

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.

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

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

Hope this helps

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

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