android-sdk - 关于HttpClient的问题,开发环境为android studio
ringa_lee
ringa_lee 2017-04-17 13:01:22
0
2
565

这个代码让我头疼了两天,在模拟器测试不行,但在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 "连接服务器失败" ;
    }

}

}

感谢解答问题的码友

ringa_lee
ringa_lee

ringa_lee

全部回覆(2)
小葫芦

我猜可能是沒有在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進行最後的工作。

刘奇

還是不合理,不該這麼複雜!不合理,建議使用Android-async-http

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板