【问题标题】:Android REST API connectionAndroid REST API 连接
【发布时间】: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


    【解决方案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 和处理响应。请参阅 Boskos 对那段代码的回答。

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

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

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      在许多应用程序中,我使用 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 用户可以帮助您。其他一切都是基于个人意见,并不具有建设性。

      【讨论】:

        猜你喜欢
        • 2019-01-05
        • 1970-01-01
        • 2018-03-29
        • 2018-04-11
        • 2020-10-27
        • 2020-06-08
        • 2017-08-02
        • 2016-09-10
        • 2017-09-23
        相关资源
        最近更新 更多