关于HttpClient的问题,开发环境为android studio


这个代码让我头疼了两天,在模拟器测试不行,但在2.3手机上测试正常,在4.X手机测试失败,最后发现可能是SDK的原因,请教怎么让其它SDK下也能使用?

< uses-permission android:name="android.permission.INTERNET" />
网络访问权限已经加上

以下代码当build.gradle文件的配置为
minSdkVersion 7
targetSdkVersion 7
正常

当build.gradle文件的配置为
minSdkVersion 9
targetSdkVersion 21
失败

在CSDN找到的资料是SDK3.X,4.X操作HttpClient,需要在子线程执行,这个真不知道该怎么做了。。。


package com.test.module;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class post {


 public static String urlpost() {
    String URL = "http://localhost/post.php";
    HttpPost httpRequest = new HttpPost(URL);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("action", "测试测试"));
    try {

        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {

            return EntityUtils.toString(httpResponse.getEntity());

        } else {
            return "连接服务器失败" ;
        }
    } catch (ClientProtocolException e) {
        return "连接服务器失败" ;

    } catch (IOException e) {
        return "连接服务器失败" ;

    } catch (Exception e) {
        return "连接服务器失败" ;
    }

}

}

感谢解答问题的码友

Android android-sdk httpclient

豪哥仔86 11 years, 2 months ago

我猜测可能是没有在 AndroidManifest.xml 中加入网络访问权限


 <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

跟着题主一起更新 (*•̀ㅂ•́)و
由于网络相关操作有可能出现延迟,为了避免不好的用户体验,通常不在UI线程里搞,而是另开线程。
比较简单的方法就是使用 AsyncTask ,下面是官网的例子:


 public class HttpExampleActivity extends Activity {
    private static final String DEBUG_TAG = "HttpExample";
    private EditText urlText;
    private TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   
        urlText = (EditText) findViewById(R.id.myUrl);
        textView = (TextView) findViewById(R.id.myText);
    }

    // When user clicks button, calls AsyncTask.
    // Before attempting to fetch the URL, makes sure that there is a network connection.
    public void myClickHandler(View view) {
        // Gets the URL from the UI's text field.
        String stringUrl = urlText.getText().toString();
        ConnectivityManager connMgr = (ConnectivityManager) 
            getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadWebpageTask().execute(stringUrl);
        } else {
            textView.setText("No network connection available.");
        }
    }

     // Uses AsyncTask to create a task away from the main UI thread. This task takes a 
     // URL string and uses it to create an HttpUrlConnection. Once the connection
     // has been established, the AsyncTask downloads the contents of the webpage as
     // an InputStream. Finally, the InputStream is converted into a string, which is
     // displayed in the UI by the AsyncTask's onPostExecute method.
     private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
       }
    }
    ...
}

嗯,就是在事件方法中创建一个 AsyncTask 子类实例,并调用其 execute 方法。
执行的就是 doInBackgound ,子线程执行完毕后会调用 onPostExecute 进行最后的工作。

熊貓要打飛機 answered 11 years, 2 months ago

Your Answer