HttpClient 是org.apache.http.* 包中的;
第一種方式使用httpclient-*.jar (需要在網上去下載httpclient-*.jar包)
把httpclient-4.5.jar/httpclient-4.4.1.jar包放入到libs里,然后點擊sync project ...才能使用httpclient-4.5.jar包
httpclient-4.5.jar不好用,建議使用httpclient-4.4.1.jar
第二種方式:配置AndroidStudio 的方式獲取 HttpClient
在相應的module下的build.gradle中加入:useLibrary 'org.apache.http.legacy'
這條語句一定要加在 android{ } 當中,然后rebulid
例如:
app/build.gradle android { useLibrary 'org.apache.http.legacy' }
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "liudeli.async"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
useLibrary 'org.apache.http.legacy'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
在AndroidManifest.xml加入權限:
<!-- 訪問網絡是危險的行為 所以需要權限 --> <uses-permission android:name="android.permission.INTERNET" /> <!-- 設置壁紙是危險的行為 所以需要權限 --> <uses-permission android:name="android.permission.SET_WALLPAPER" />
MainActivity6:
package liudeli.async; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity6 extends Activity implements View.OnClickListener { private EditText etName; private EditText etPwd; private Button btLogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main6); etName = findViewById(R.id.et_name); etPwd = findViewById(R.id.et_pwd); btLogin = findViewById(R.id.bt_login); btLogin.setOnClickListener(this); } // 請求服務器的地址 private final String PATH = "http://127.0.0.1:8080/LoginServlet"; @Override public void onClick(View v) { // 拼裝參數 final Map<String, String> map = new HashMap<>(); map.put("name", etName.getText().toString()); map.put("pwd", etPwd.getText().toString()); // 聯網操作必須開啟線程,執行異步任務 new Thread(){ @Override public void run() { super.run(); try { // Get請求方式,參數操作是拼接在鏈接 loginByGet(PATH, map); // Post請求方式,參數操作是封裝實體對象 loginByPost(PATH, map); } catch (Exception e) { e.printStackTrace(); threadRunToToast("登錄是程序發生異常"); } } }.start(); } /** * HttpClient Get 方式請求 * @param path 請求的路徑 * @param map 請求的參數 * 拼接后的完整路徑:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456 */ private void loginByGet(String path, Map<String, String> map) throws Exception{ // 拼接路徑 拼接后的完整路徑:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456 StringBuffer pathString = new StringBuffer(path); pathString.append("?"); // 迭代遍歷Map for (Map.Entry<String, String> mapItem : map.entrySet()) { String key = mapItem.getKey(); String value = mapItem.getValue(); // name=zhangsan& pathString.append(key).append("=").append(value).append("&"); } // name=zhangsan&pwd=123456& 刪除最后一個符號& 刪除后:name=zhangsan&pwd=123456 pathString.deleteCharAt(pathString.length() - 1); // 最后完整路徑是:http://127.0.0.1:8080/LoginServlet?name=zhangsan&pwd=123456 // 第一步 創建HttpClient HttpClient httpClient = new DefaultHttpClient(); // 第三步 創建請求對象 Get HttpUriRequest getRequest = new HttpGet(pathString.toString()); // 第二步 執行請求,獲取響應對象 HttpResponse response = httpClient.execute(getRequest); // 第四步 判斷請求是否成功 if (response.getStatusLine().getStatusCode() == 200) { // 第五步 獲取響應的流 InputStream inputStream = response.getEntity().getContent(); byte[] bytes = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (-1 != (len = inputStream.read())) { // 把存取到bytes的數據,寫入到>>ByteArrayOutputStream bos.write(bytes, 0, len); } // 第六步 判斷是否請求成功, 注意:⚠️ success 是自定義服務器返回的 success代表登錄成功 String loginResult = bos.toString(); if ("success".equals(loginResult)) { // 不能子在子線程中Toast // Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄成功"); } else { // 不能子在子線程中Toast // Toast.makeText(this, "登錄失敗", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄失敗"); } // 第七步 關閉流 inputStream.close(); bos.close(); } else { // 不能子在子線程中Toast // Toast.makeText(this, "登錄失敗,請檢查網絡!", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄失敗,請檢查網絡!"); } } /** * HttpClient Get 方式請求 * @param path 請求的路徑 * @param map 請求的參數 * 路徑:http://127.0.0.1:8080/LoginServlet * * 參數: * name=zhangsan * pwd=123456 */ private void loginByPost(String path, Map<String, String> map) throws Exception { // 第一步 創建HttpClient HttpClient httpClient = new DefaultHttpClient(); // 第三步 創建請求對象 Post HttpPost postRequest = new HttpPost(path); // 第六步 參數封裝操作 List<NameValuePair> nameValuePairs = new ArrayList<>(); for (Map.Entry<String, String> mapItem : map.entrySet()) { // 遍歷Map集合里面的 key value >>> name=zhangsan pwd=123456 String key = mapItem.getKey(); String value = mapItem.getValue(); // 創建參數對象 NameValuePair nameValuePair = new BasicNameValuePair(key, value); // 把參數對象放入List<NameValuePair>集合 nameValuePairs.add(nameValuePair); } // 第五步 創建實體對象 傳入參數>>>List<? extends NameValuePair> HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8"); // 第四步 把請求的參數 放入實體 postRequest.setEntity(entity); // 第二步 執行請求,獲取響應對象 HttpResponse response = httpClient.execute(postRequest); // 第七步 判斷請求是否成功 if (response.getStatusLine().getStatusCode() == 200) { // 第八步 獲取響應的流 InputStream inputStream = response.getEntity().getContent(); byte[] bytes = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while (-1 != (len = inputStream.read())) { // 把存取到bytes的數據,寫入到>>ByteArrayOutputStream bos.write(bytes, 0, len); } // 第九步 判斷是否請求成功, 注意:⚠️ success 是自定義服務器返回的 success代表登錄成功 String loginResult = bos.toString(); if ("success".equals(loginResult)) { // 不能子在子線程中Toast // Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄成功"); } else { // 不能子在子線程中Toast // Toast.makeText(this, "登錄失敗", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄失敗"); } // 第十步 關閉流 inputStream.close(); bos.close(); } else { // 不能子在子線程中Toast // Toast.makeText(this, "登錄失敗,請檢查網絡!", Toast.LENGTH_SHORT).show(); threadRunToToast("登錄失敗,請檢查網絡!"); } } /** * 在 主線程 子線程 中提示,屬於UI操作 */ private void threadRunToToast(final String text) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } }); } }
activity_main6.xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="姓名" /> <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密碼" /> <EditText android:id="@+id/et_pwd" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> <Button android:id="@+id/bt_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:text="login" /> </LinearLayout>