首先上效果图客户端
服务端
- Get一般用于从服务器取数据,而且不改变原来的内容;
- Post一般用于向服务器传递数据,会改变服务器的内容。
- 从安全性上考虑,Get的安全性要稍微差点,因为它会把用户信息直接在地址栏显示出来。(但是Android程序开发没有地址栏啊,这个是否可以不予考虑)。但如果对信息的安全性要求比较高的话,比如含有用户的账号信息,或者敏感信息,这个时候优先考虑使用Post。
- 基本流程
- 综合,如果没有特殊需要,用Get,方便
- 首先服务端创建LoginServlet用来验证客户端返回用户信息,如果用户名跟密码通过则返回Code:1登录成功返回给客户端,否则登录失败!提示用户名或者密码错误
- public void init() throws ServletException {
// Put your code here
super.init();
map=new HashMap<String, String>();
map.put("admin", "123");
map.put("tom", "123456");
map.put("sy", "666");
}
- 初始化用户名跟密码并保存在map集合中
- 然后条用doPost方法
- public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码集
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
String pwd=request.getParameter("password");
boolean isExist=false;
// 通过客户端返回的用户名跟密码进行登录验证
for (String username : map.keySet()) {
System.out.println("username:"+username);
if (name.equals(username)) {
System.out.println(map.get(username)+2);
//
if (pwd.equals(map.get(username))) {
System.out.println("验证成功");
isExist = true;
}
}
}
System.out.println(isExist);
// code:1 验证成功 code 0验证失败
if (isExist == true) {// 用户名存在验证成功
String jsonString = "{code : 1}";
out.write(jsonString);
} else {// 用户名或密码错误
String jsonString = "{code : 0} ";
out.write(jsonString);
}
}
客户端代码: - LoginActivity
- package com.weixin;
import java.util.HashMap;
import java.util.Map;
import com.weixin.util.HttpTools;
import com.weixin.util.HttpurlTools;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final String TAG="LoginActivity";
private EditText et_name,et_pwd;
private Button btn_login;
private String name,pwd;
private Map<String,String> map;
//192.168.0.190服务端的url
private String url="http://192.168.0.190:8080/UploadTask/LoginServlet";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//输入时隐藏小键盘
initView();
// InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow(et_name.getWindowToken(), 0);
// imm.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0);
}
private void initView() {
//初始化操作
et_name=(EditText) findViewById(R.id.et_name);
et_pwd=(EditText) findViewById(R.id.et_pwd);
btn_login=(Button) findViewById(R.id.btn_login);
}
public void Login(View v){ - //通过客户端发送get或者post两种请求方式输入用户名跟密码返回code信息验证用户登录成功返回1失败返回0
- name=et_name.getText().toString().trim();
pwd=et_pwd.getText().toString().trim();
map=new HashMap<String, String>();
map.put("name", name);
map.put("password",pwd);
new MyTask().execute(url);
}
class MyTask extends AsyncTask<String, Void, Integer>{
@Override
protected Integer doInBackground(String... params) {
// 在后台执行
//int code=HttpTools.getMethod(params[0], map);
//int code = HttpTools.postMethod(params[0], map);
//int code = HttpurlTools.doGet(params[0], map);
int code = HttpurlTools.postMethod(params[0], map);
return code;
}
@Override
protected void onPreExecute() {
// 首先执行
super.onPreExecute();
}
@Override
protected void onPostExecute(Integer result) {
//
super.onPostExecute(result);
if(result==0){
Toast.makeText(LoginActivity.this, "用戶名跟密码不正确", 0).show();
Log.i(TAG, ""+result);
}else if(result==1){
Toast.makeText(LoginActivity.this, "登录成功", 0).show();
Log.i(TAG, ""+result);
}
}
}
}
- HttpurlTools
package com.weixin.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class HttpurlTools {
/**
* get方式
* @param murl
* @param map
* @return
*/
public static int doGet(String murl,Map<String,String> map){
int code=0;
StringBuffer sb=new StringBuffer(murl+"?");
for(String key:map.keySet()){
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);//截取最後一個&
String mruls=sb.toString();
try {
URL url=new URL(mruls);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
//允許輸入流
conn.setDoInput(true);
//允許輸出流
//conn.setDoOutput(true);
//get請求方式
conn.setRequestMethod("GET");
//設置不緩存
conn.setUseCaches(false);
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
conn.setRequestProperty("Content-type",
"application/x-java-serialized-object");
// 连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
StringBuffer buffer=new StringBuffer();
String line;
while((line=br.readLine())!=null){
buffer.append(line);
}
JSONObject jsonObject=new JSONObject(buffer.toString());
code=jsonObject.getInt("code");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
public static int postMethod(String murl,Map<String,String> map){
int code=0;
StringBuffer sb=new StringBuffer();
for(String key:map.keySet()){
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);
String params=sb.toString();
try {
URL url = new URL(murl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内需要设为true,
// 默认情况下是false;
connection.setDoOutput(true);
// post方式不支持缓存
connection.setUseCaches(false);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream(), "utf-8"));
bw.write(params);
bw.flush();
bw.close();
// 调用此方法就不必再使用conn.connect()方法
int responseCode = connection.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString());
code = jsonObject.getInt("code");
} else {
Log.i("error", "访问失败");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class HttpurlTools {
/**
* get方式
* @param murl
* @param map
* @return
*/
public static int doGet(String murl,Map<String,String> map){
int code=0;
StringBuffer sb=new StringBuffer(murl+"?");
for(String key:map.keySet()){
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);//截取最後一個&
String mruls=sb.toString();
try {
URL url=new URL(mruls);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
//允許輸入流
conn.setDoInput(true);
//允許輸出流
//conn.setDoOutput(true);
//get請求方式
conn.setRequestMethod("GET");
//設置不緩存
conn.setUseCaches(false);
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
conn.setRequestProperty("Content-type",
"application/x-java-serialized-object");
// 连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
StringBuffer buffer=new StringBuffer();
String line;
while((line=br.readLine())!=null){
buffer.append(line);
}
JSONObject jsonObject=new JSONObject(buffer.toString());
code=jsonObject.getInt("code");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
public static int postMethod(String murl,Map<String,String> map){
int code=0;
StringBuffer sb=new StringBuffer();
for(String key:map.keySet()){
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);
String params=sb.toString();
try {
URL url = new URL(murl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内需要设为true,
// 默认情况下是false;
connection.setDoOutput(true);
// post方式不支持缓存
connection.setUseCaches(false);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream(), "utf-8"));
bw.write(params);
bw.flush();
bw.close();
// 调用此方法就不必再使用conn.connect()方法
int responseCode = connection.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString());
code = jsonObject.getInt("code");
} else {
Log.i("error", "访问失败");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
}
HttpTools
package com.weixin.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.android.volley.toolbox.HttpStack;
public class HttpTools {
/**
* get请求方式
* @param url
* @param map
* @return
*/
public static int getMethod(String url,Map<String,String> map){
HttpClient httpClient=new DefaultHttpClient();
int code=0;
StringBuffer sb=new StringBuffer(url+"?");
for (String key : map.keySet()) {
//获取map集合中key
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);//截取最后一个&
String murl=sb.toString();
try {
HttpGet get=new HttpGet(murl);
//执行get方式
HttpResponse response=httpClient.execute(get);
int requestCode=response.getStatusLine().getStatusCode();
if(requestCode==HttpStatus.SC_OK){
HttpEntity entity=response.getEntity();
//传回来一个json
String jsonentity=EntityUtils.toString(entity);
Log.i("tag", jsonentity.toString());
JSONObject jsonObject=new JSONObject(jsonentity);
code=jsonObject.getInt("code");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
/**
* post請求
* @param url
* @param map
* @return
*/
public static int postMethod(String url,Map<String,String> map){
// code为1登陆成功 0登陆失败
HttpClient httpClient = new DefaultHttpClient();
int code = 0;
List<NameValuePair> mList = new ArrayList<NameValuePair>();
for (String key : map.keySet()) {
String value = map.get(key);
mList.add(new BasicNameValuePair(key, value));
}
try {
// 使用HttpPost对象设置发送的URL路径
HttpPost httpPost = new HttpPost(url);
// 把请求参数变成请求体部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(mList, "utf-8");
// 使用HttpPost对象设置发送的URL路径
httpPost.setEntity(uee);
HttpResponse response = httpClient.execute(httpPost);
int resultCode = response.getStatusLine().getStatusCode();
if (resultCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// 传回来的是一个json数据
String jsonEntity = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(jsonEntity);
code = jsonObject.getInt("code");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
}
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.android.volley.toolbox.HttpStack;
public class HttpTools {
/**
* get请求方式
* @param url
* @param map
* @return
*/
public static int getMethod(String url,Map<String,String> map){
HttpClient httpClient=new DefaultHttpClient();
int code=0;
StringBuffer sb=new StringBuffer(url+"?");
for (String key : map.keySet()) {
//获取map集合中key
String value=map.get(key);
sb.append(key+"="+value);
sb.append("&");
}
sb.deleteCharAt(sb.length()-1);//截取最后一个&
String murl=sb.toString();
try {
HttpGet get=new HttpGet(murl);
//执行get方式
HttpResponse response=httpClient.execute(get);
int requestCode=response.getStatusLine().getStatusCode();
if(requestCode==HttpStatus.SC_OK){
HttpEntity entity=response.getEntity();
//传回来一个json
String jsonentity=EntityUtils.toString(entity);
Log.i("tag", jsonentity.toString());
JSONObject jsonObject=new JSONObject(jsonentity);
code=jsonObject.getInt("code");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return code;
}
/**
* post請求
* @param url
* @param map
* @return
*/
public static int postMethod(String url,Map<String,String> map){
// code为1登陆成功 0登陆失败
HttpClient httpClient = new DefaultHttpClient();
int code = 0;
List<NameValuePair> mList = new ArrayList<NameValuePair>();
for (String key : map.keySet()) {
String value = map.get(key);
mList.add(new BasicNameValuePair(key, value));
}
try {
// 使用HttpPost对象设置发送的URL路径
HttpPost httpPost = new HttpPost(url);
// 把请求参数变成请求体部分
UrlEncodedFormEntity uee = new UrlEncodedFormEntity(mList, "utf-8");
// 使用HttpPost对象设置发送的URL路径
httpPost.setEntity(uee);
HttpResponse response = httpClient.execute(httpPost);
int resultCode = response.getStatusLine().getStatusCode();
if (resultCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
// 传回来的是一个json数据
String jsonEntity = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(jsonEntity);
code = jsonObject.getInt("code");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
}