Android Post和使用apache获取数据

时间:2013-11-16 09:38:29

标签: android apache post get

我引用了这个...... Android HttpClient, DefaultHttpClient, HttpPost  ,http://www.androidsnippets.com/executing-a-http-post-request-with-httpclienthttp://www.javacodegeeks.com/2013/06/android-apache-http-client.html链接... 他们指定传递url并且他们没有指定传递参数... 当我实现上面url中给出的代码时,我得到了这个错误......我是新手... 我称这种方法......

   public void postData() {
    String res="";
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", ""));
        nameValuePairs.add(new BasicNameValuePair("email", ""));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        Log.e("response",""+response);


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

} 

请帮帮我...    感谢..

1 个答案:

答案 0 :(得分:1)

由于你没有包含错误,我认为这是因为你阻止了在旧版Android上工作正常的UI线程,但是在最新版本中你将不得不使用AsyncTask来做你的发布请求。

private class MyPostTask extends AsyncTask<URL, Void, Void> {
     protected Long doInBackground(URL... urls) {
         String res="";
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(urls.get(0));

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", ""));
            nameValuePairs.add(new BasicNameValuePair("email", ""));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.e("response",""+response);


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

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

发出请求:

new MyPostTask().execute("http://example.com/foo/bar/");