Android - 单独线程上的 HTTP GET

Android - HTTP GET on separate thread

背景: 我是 android 编程新手。我想简单地向本地服务器发送一个 http get 请求。

我想将名称作为参数传递给此请求,并希望在 json 中获得一个 return。这个问题我无法在主线程上执行它。我该怎么做?

这是我尝试过的:

主要class:

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

在同一文件中分隔 class:

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
        }

我不确定这是否是完成此任务的好方法。我也不知道怎么称呼它。

您应该了解 asyncTask 的工作原理。在 DoInBackground 中,您应该将代码引用到 HTTPRequest。我建议使用方法来提高对代码的理解。这是我的一个应用程序的示例:

 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
     }
 }

然后在 activity onCreate() 方法中执行 Asynktask。

 new MyAsyncTask().execute("    ");

您可以在此处阅读有关 AsyncTask 的更多信息: AsyncTask Android Developer

AsyncTask 允许您在不同的线程中执行后台操作而无需操作 threads/handlers。

应该是这样的:

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
     }
}

然后你可以执行一个AsyncTask:

new httpGet().execute(ParamForDoInBackground);

您可以参考以下内容:AndroidBackgroundProcessing and Android Developer AsyncTask