【问题标题】:Android - HTTP GET on separate threadAndroid - 单独线程上的 HTTP GET
【发布时间】:2015-07-31 01:35:30
【问题描述】:

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

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

这是我尝试过的:

主类:

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

同一文件中的单独类:

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
        }

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

【问题讨论】:

    标签: java android multithreading http-get


    【解决方案1】:

    AsyncTask 允许您在不同的线程中执行后台操作,而无需操作线程/处理程序。

    应该是这样的:

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

    您可以参考以下内容:AndroidBackgroundProcessingAndroid Developer AsyncTask

    【讨论】:

    • 您的最后一行不正确。应该是new httpGet().execute(ParamForDoInBackground)
    【解决方案2】:

    您应该了解 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
         }
     }
    

    然后在您的活动 onCreate() 方法中执行 Asynktask。

     new MyAsyncTask().execute("    ");
    

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

    【讨论】:

      猜你喜欢
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多