这是一个简单实现了Android客户端与服务端交互-客户端GET方式登录和客户端POST方式查询的一个小案例
package com.jxust.day06;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import com.jxust.day06.entity.User;
/**
* Servlet implementation class Login_Servlet
*/
@WebServlet("/Login_Servlet")
public class Login_Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
List<User> users;
User user;
private static final String NAME = "name";
private static final String PASSWORD = "password";
/**
* @see HttpServlet#HttpServlet()
*/
public Login_Servlet() {
super();
users = new ArrayList<>();
user = new User("张飞", '男', 33, 1.99, "123456");
users = new ArrayList<>();
users.add(user);
users.add(new User("王菲", '女', 33, 1.69, "123456"));
users.add(new User("刘亦菲", '女', 30, 1.71, "123456"));
users.add(new User("李菲", '女', 31, 1.68, "123456"));
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter(NAME);
if(name == null){
return ;
}
name =new String(name.getBytes("iso8859-1"),"utf-8");
System.out.println("name="+name);
String password = request.getParameter(PASSWORD);
System.out.println("password="+password);
for(int i = 0;i < users.size();i++){
User user = users.get(i);
if(name.equals(user.getName()) && password.equals(user.getPassword()) ){
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getOutputStream(), user); //服务器通过输出流发送给客户端
System.out.println(user.toString());
return ;
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter(NAME);
List<User> list = new ArrayList<>();
for(User user : users){
if(user.getName().indexOf(name) >= 0){ // 就是name在user的集合中
list.add(user);
}
}
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getOutputStream(), list);
System.out.println("查询结束");
}
}
package com.jxust.day06_03_httpurlconnectiondemo;
import java.io.IOException;
public class MainActivity extends Activity {
// 不能写localhost而应该写模拟机的地址10.0.2.2,如果是真机,那么就要写真机的地址
// 访问的网络地址
private static final String PATH = "http://10.0.2.2:8080/Day06_Servlet/Login_Servlet";
EditText metName, metPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setListener();
}
private void setListener() {
setLoginOnClickListener();
setQueryOnClickListener();
}
private void setQueryOnClickListener() {
findViewById(R.id.btnQuery).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
public void run() {
String name = metName.getText().toString();
name = "name="+name;
try {
byte[] data = name.getBytes("utf-8");
URL url = new URL(PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoOutput(true); // doGet中是不需要设置的,但是doPost是需要设置的
OutputStream out = conn.getOutputStream();
out.write(data);
out.flush();
if (conn.getResponseCode() != 200) {
return;
}
ObjectMapper om = new ObjectMapper();
List<User> users = om.readValue(conn.getInputStream(), List.class);
Log.i("main", users.toString());
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} // 将类型转换成utf-8的格式
catch (IOException e2) {
e2.printStackTrace();
}
}
}.start();
}
});
}
private void setLoginOnClickListener() {
findViewById(R.id.btnLogin).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 创建一个工作线程,因为如果不在工作线程内访问网络有可能会出现异常
new Thread() {
public void run() {
String name = metName.getText().toString();
String password = metPassword.getText().toString();
StringBuilder sb = new StringBuilder(PATH);
sb.append("?name=").append(name).append("&password=").append(password);
try {
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000); // 读取服务端的时间为5秒钟,如果超过时间就断开服务端连接
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) {
// Toast.makeText(MainActivity.this,
// "连接服务端失败",
// 2000).show();
return;
}
ObjectMapper om = new ObjectMapper();
User user = om.readValue(conn.getInputStream(), User.class); // 按User这个类型来解析
Log.i("main", user.toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}.start();
}
});
}
private void initView() {
metName = (EditText) findViewById(R.id.etName);
metPassword = (EditText) findViewById(R.id.etPassword);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入姓名" android:text="菲"/> <EditText android:id="@+id/etPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入登陆密码" android:text="123456" android:password="true"/> <Button android:id="@+id/btnLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="GET方式登陆" /> <Button android:id="@+id/btnQuery" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="POST方式查询" /> </LinearLayout>
package com.jxust.day06.entity;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private char sex;
private int age;
private double height;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
// TODO Auto-generated constructor stub
}
public User(String name, char sex, int age, double height, String password) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.height = height;
this.password = password;
}
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", age=" + age
+ ", height=" + height + ", password=" + password + "]";
}
}