在Android中发送HTTP请求

时间:2012-10-30 05:01:29

标签: php android web-services

我正在向服务器中的PHP站点发送HTTP请求。但是当我发送请求时,手机卡住了几秒钟。有时它会花很长时间发送和接收请求的结果。

如何解决这个问题。请帮我找到解决方案。感谢。

这是我试过的代码......

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

}

4 个答案:

答案 0 :(得分:1)

要发出http请求,您必须使用AsyncTask。这将在后台运行。

请参阅以下链接以供参考

http://www.vogella.com/articles/AndroidPerformance/article.html

答案 1 :(得分:0)

使用AsyncTask从UI线程发出http请求。将您的代码更改为:

private class LongOperation extends AsyncTask<String, Void, String> {

          @Override
          protected Void doInBackground(String... params) {

              //Call your post method here
                  postData();

                  return null;
          }      

          @Override
          protected void onPostExecute(String result) {
              // get result after operation complete
          }

          @Override
          protected void onPreExecute() {
          }

          @Override
          protected void onProgressUpdate(Void... values) {
          }
    }   

答案 2 :(得分:0)

您应该在网络线程以外的其他线程中执行网络操作,请参阅处理程序和异步任务。

http://developer.android.com/training/basics/network-ops/connecting.html#AsyncTask

http://developerlife.com/tutorials/?p=290

答案 3 :(得分:0)

尝试这样,您可以使用:HttpClient.exeucute(httpPost)并获取       的HttpResponse

这项工作对我来说很完美。

DefaultHttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    pairs.add(new BasicNameValuePair("email", stringeditemail));

    UrlEncodedFormEntity formEntity = null;
    try {
        formEntity = new UrlEncodedFormEntity(params);

    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    post.setEntity(formEntity);

    try {

        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            return iStream_to_String(is);
        } else {
            return "Hello This is status ==> :"
                    + String.valueOf(statusCode);
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;

}

并创建将stringbuilder转换为字符串

的方法
 public static String iStream_to_String(InputStream is1) {
    BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
    String line;
    StringBuilder sb = new StringBuilder();
    try {
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String contentOfMyInputStream = sb.toString();
    return contentOfMyInputStream;
}