【问题标题】:Android Post and Get Data using apacheAndroid 使用 apache 发布和获取数据
【发布时间】:2013-11-16 09:38:28
【问题描述】:

我已经参考了这个... Android HttpClient, DefaultHttpClient, HttpPosthttp://www.androidsnippets.com/executing-a-http-post-request-with-httpclienthttp://www.javacodegeeks.com/2013/06/android-apache-http-client.html 链接... 他们已经指定传递 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
    }

} 

请帮帮我... 谢谢..

【问题讨论】:

  • 请分享你的代码和你得到的错误
  • 感谢您的快速回复..我发布了我的代码..请看看..

标签: android apache post get


【解决方案1】:

由于您没有包含错误,我认为这是因为您阻止了 UI 线程,该线程在旧版本的 android 上运行良好,但在最新版本中,您必须使用 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/");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多