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>