您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
42_采用httpclient发送get请求
发布时间:2021-02-25 13:58:30编辑:雪饮阅读()
下载org.apache.http.client.HttpClient
此时就需要自己处理依赖了,挂上梯子然后操作如:
这里输入框下方有提示匹配搜索规则,假如这里我要搜索的是org.apache.http…,后面具体是httpxxx或者http.xxx都可以匹配到
这里我就选择这个4.2.1了,然后应用它,等依赖fetching完成就ok了
采用httpclient发送get请求
org.apache.http.client.HttpClient的import问题解决完成后就开始实现其的get请求接口了。
啦第一步咯,要增加一个新按钮用于HttpClient的调用,则其元素值配置strings.xml:
<resources>
<string name="app_name">Login</string>
<string name="input_name">请输入用户名</string>
<string name="input_password">请输入密码</string>
<string name="get_login">采用get方式登陆</string>
<string name="post_login">采用post方式登陆</string>
<string name="client_get_login">httpclient的get登陆</string>
</resources>然后布局文件上添加这个新的按钮activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/input_name" />
<EditText
android:id="@+id/et_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/input_password" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/get_login"
android:id="@+id/bt_login"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/post_login"
android:id="@+id/bt_login_post"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/client_get_login"
android:id="@+id/bt_login_client_get"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
</LinearLayout>然后DataService.java中实现httpClient以get请求的具体代码:
package com.example.login;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class DataService {
/**
* ͨ通过get请求提交数据到服务器
*
* @param path
* 服务器servlet地址
* @param name
* 用户名
* @param password
* 密码
* @return 服务器返回回来的string数据
*/
public static String sendDataByGet(String path, String name, String password)
throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
// 数据并没有发送给服务器
// 获取服务器返回的流信息
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
// get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
// post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
/**
* 采用post的方式 提交数据到服务器
*
* @param path
* 服务器servlet的地址
* @param name
* 用户名
* @param password
* 密码
* @return 服务器返回的数据信息
* @throws Exception
*/
public static String sendDataByPost(String path, String name,
String password) throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = "name=" + param1 + "&password=" + param2;
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
// 设置 http协议可以向服务器写数据
conn.setDoOutput(true);
// 设置http协议的消息头
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
// 把我们准备好的data数据写给服务器
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
// httpurlconnection 底层实现 outputstream 是一个缓冲输出流
// 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
} else {
throw new IllegalStateException("服务器状态异常");
}
}
/**
* httpclient 浏览器的简单包装
* new HttpClient 就相当于得到了一个浏览器
*/
public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
//1. 获取到一个浏览器的实例
HttpClient client = new DefaultHttpClient();
//2. 准备请求的地址
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
//3.发请求
HttpResponse ressponse = client.execute(httpGet);
int code = ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
else{
throw new IllegalStateException("服务器状态异常");
}
}
}然后主程序中再增加对应的事件处理MainActivity.java:
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mEtName;
private EditText mEtPassword;
private Button mBtLogin;
private Button mBtLoginPost;
private Button mBtLoginClientGet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtName = this.findViewById(R.id.et_name);
mEtPassword = this.findViewById(R.id.et_password);
mBtLogin = this.findViewById(R.id.bt_login);
mBtLogin.setOnClickListener(this);
mBtLoginPost = this.findViewById(R.id.bt_login_post);
mBtLoginPost.setOnClickListener(this);
mBtLoginClientGet = (Button)this.findViewById(R.id.bt_login_client_get);
mBtLoginClientGet.setOnClickListener(this);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
String name = mEtName.getText().toString().trim();
String password = mEtPassword.getText().toString().trim();
if("".equals(name)||"".equals(password)){
Toast.makeText(this, "用户名或密码不能为空", 0).show();
return;
}
String path = getResources().getString(R.string.servleturl);
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
switch (v.getId()) {
case R.id.bt_login:
// 通过get请求 发送数据到服务器
try {
String result = DataService.sendDataByGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_post:
try {
String result = DataService.sendDataByPost(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_client_get:
try {
String result = DataService.sendDataByHttpClientGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "访问网路异常", 0).show();
e.printStackTrace();
}
break;
}
}
}最后就是部署到设备中进行测试咯
关键字词:httpclient,get,android