Android REST API连接

时间:2013-12-26 12:51:38

标签: java android json api rest

我有点愚蠢 - 为此呀。

我写了一个API,它给了一些JSON。我的目标是从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());
    }


}

2 个答案:

答案 0 :(得分:1)

  

我有点愚蠢 - 为此呀。

不要傻,每个人都必须从学习的地方开始:)

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

我回答了similar question一段时间,但同样的代码适用,请参阅下面的内容。

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

}

onCreateonClickListener设置为按钮,按下按钮时会创建一个新的AsyncTask并调用execute()

doInBackground在一个单独的线程上运行,因此您可以在此处执行长时间运行的任务,例如调用REST API和处理响应。见博斯科斯&#39;回答那段代码。

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

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

希望这有帮助

答案 1 :(得分:0)

在许多应用程序中,我使用AsyncTask与API和IMO进行通信AsyncTask方法有很多好处。
以下是通过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;
        }
    }

您必须发布代码并指出问题,然后SO用户可以帮助您。其他一切都是以个人观点为基础的,而且不具有建设性。