简体   繁体   English

Android-单独线程上的HTTP GET

[英]Android - HTTP GET on separate thread

Background: I am new to android programming. 背景:我是android编程的新手。 I want to simply do an http get request to a local server. 我只想对本地服务器执行http get请求。

I want to pass this request a name as a parameter and want to get a return in json. 我想将此请求的名称作为参数传递,并希望在json中返回。 This issue that I cannot execute it on the main thread. 我无法在主线程上执行此问题。 How can I do this? 我怎样才能做到这一点?

Here is what I tried: 这是我尝试过的:

main class: 主类:

itemsAdapter.add(get.getName(device.getName()));

Seperate class in same file: 同一文件中的单独类:

private class httpGet extends AsyncTask<Editable, Void, Integer> {
        protected String doInBackground(Editable... params) {
            Editable editable = params[0];
            return getName(editable.toString());
        }
        final String getName(String btName) {
            HttpResponse response = null;
            String result = "";
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
                request.setURI(website);
                response = client.execute(request);
                // Convert String to json object
                JSONObject json = new JSONObject(response.toString());

                // get LL json object
                JSONObject json_Name = json.getJSONObject("Name");

                // get value from LL Json Object
                name = json_Name.getString("value"); //<< get value here
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
                // Do something to recover ... or kill the app.
            }

            return result;
        }

        protected void onPostExecute(Integer result) {
            // here you have the result
        }

I am not sure if this is even a good way to do this task. 我不确定这是否是完成此任务的好方法。 I also have no idea how I would call it. 我也不知道我怎么称呼它。

You should learn how the asyncTask work. 您应该了解asyncTask的工作方式。 Inside DoInBackground you should to put the code referent to the HTTPRequest. 在DoInBackground内部,应该将引用的代码放在HTTPRequest中。 I recommend to use methods to improve the understanding of code. 我建议使用方法来提高对代码的理解。 Here is an example of one of my apps: 这是我的一个应用程序的示例:

 public String query(String uri) {
    HttpClient cliente = new DefaultHttpClient();
    HttpContext contexto = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(uri);
    HttpResponse response = null;
    String resultado=null;

    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("dato", cod_restaurante));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        response = cliente.execute(httpPost, contexto);
        HttpEntity entity = response.getEntity();
        resultado = EntityUtils.toString(entity, "UTF-8");


    } catch (Exception e) {
        // TODO: handle exception
    }
    return resultado;
}

 private class MyAsyncTask extends AsyncTask<String, Integer, String>{

    @Override
    protected String doInBackground(String... params) 
    {
        result=query(params[0]);
        return result;
    }

    protected void onPostExecute(final String resultadoDoInBackground)
    { 
      //here put the code to modify the UI
     }
 }

Then in your activity onCreate() method you execute the Asynktask. 然后在您的活动onCreate()方法中执行Asynktask。

 new MyAsyncTask().execute("    ");

You can read more about AsyncTask here: AsyncTask Android Developer 您可以在此处阅读有关AsyncTask的更多信息: AsyncTask Android开发人员

AsyncTask allows you to perform a background operation in a different thread without manipulating threads/handlers. AsyncTask允许您在其他线程中执行后台操作,而无需操纵线程/处理程序。

It should be this way: 应该是这样的:

private class httpGet extends AsyncTask<ParamForDoInBackground, ParamForOnProgressUpdate, ParamForOnPostExecute> {
     protected Long doInBackground(ParamForDoInBackground... urls) {
        // do the request here
     }

     protected void onProgressUpdate(ParamForOnProgressUpdate progress) {
        // if you need to show any progress of the 
        // request from doInBackground
     }

     protected void onPostExecute(ParamForOnPostExecute result) {
        // this method will run when doInBackground
        // is done executing
     }
}

Then you can execute an AsyncTask: 然后,您可以执行AsyncTask:

new httpGet().execute(ParamForDoInBackground);

You can use the following as a reference: AndroidBackgroundProcessing and Android Developer AsyncTask 您可以使用以下内容作为参考: AndroidBackgroundProcessingAndroid开发人员AsyncTask

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

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