Android HttpClient只使用get请求将数据发送到服务器

时间:2012-05-26 07:19:18

标签: android get httpclient

我想使用Android访问参数化网址。它所要做的就是“加载”页面,使其完成它应该做的事情(用给定参数更新数据库)。

我在加载网址时遇到了麻烦,因此我观看了有关常规HttpClient活动的视频 - 只是等待响应并收集该信息。我认为它仍然会加载页面,因此也让该页面执行。我甚至无法正确运行页面或收集回复。

这是我使用的代码:

String url = "http://www.removed.com?param1="+param1+"&param2="+param2;

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            InputStream webs = entity.getContent();
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8 );
                test.setText(reader.readLine());
                webs.close();
            }catch(Exception e) {
                Log.e("Error in conversion: ", e.toString());
            }
        }catch(Exception e) {
            Log.e("Error in connection: ", e.toString());
        }

请让我知道如何让它执行页面并更新数据库。如果我将参数手动输入浏览器,它就可以工作。

2 个答案:

答案 0 :(得分:2)

你还没有发布你正在运行的地方或错误是什么,但首先想到的两件事是:

  • 您是否在清单中设置了INTERNET权限?
  • 如果这是Honeycomb,这是在一个单独的线程中运行吗? - 从3.0开始,您无法在主显示线程中运行HTTP请求。

答案 1 :(得分:0)

在回答您的评论后,我认为您正在搜索回复代码。我在这里发布你的代码,这在我的代码中运行良好

String urlGET = "http://www.removed.com?param1="+param1+"&param2="+param2;

HttpGet getMethod = new HttpGet(urlGET);
    // if you are having some headers in your URL uncomment below line 
    //getMethod.addHeader("Content-Type", "application/form-data");
    HttpResponse response = null;
    HttpClient httpClient = new DefaultHttpClient();
    try {
        response = httpClient.execute(getMethod);

        int responseCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String responseBody = null;

        if (entity != null) {
            responseBody = EntityUtils.toString(entity);
          //here you get response returned from your server
            Log.e("response = ", responseBody);

            // response.getEntity().consumeContent();

        }
        JSONObject jsonObject = new JSONObject(responseBody);
         // do whatever you want to do with your json reponse data

        }
        catch(Exception e)
        {
        e.printStackTrace();
        }