get方法来传递数据
一、项目介绍
主要是模拟qq登录,像服务器发送登录数据,如果数据相等,则登录成功。
二、项目架构
客户端Eclipse中
StreamTool.java 主要功能是将返回的数据流转化为数据串的工具类
源码:
MainActivity.java:
package com.lcz.login_in;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import com.lcz.newsclient.utils.StreamTool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
private Button login;
private EditText ed_number;
private EditText ed_pwd;
private TextView tv_status;
private String path="http://192.168.43.125:8080/Web/servlet/login?";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button) findViewById(R.id.login);
login.setOnClickListener(this);
ed_number=(EditText) findViewById(R.id.ed_number);
ed_pwd=(EditText) findViewById(R.id.ed_pwd);
tv_status=(TextView) findViewById(R.id.login_status);
}
private Handler mHandler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
String data=(String) msg.obj;
tv_status.setText(data);
break;
case ERROR:
Toast.makeText(MainActivity.this, "连接错误", 0).show();
break;
default:
break;
}
};
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//获得qq号码和密码,然后登录
final String number = ed_number.getText().toString().trim();
final String pwd=ed_pwd.getText().toString().trim();
if(TextUtils.isEmpty(number)||(TextUtils.isEmpty(pwd))){
Toast.makeText(this, "号码或密码不能为空", 0).show();
return;
}
//走到这里,说明qq号码和密码都输入了,然后需要连接网络
new Thread(){
public void run() {
try {
path=path+"number="+URLEncoder.encode(number,"UTF-8")+"&pwd="+URLEncoder.encode(pwd,"UTF-8");
URL url=new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
//流转换为字符串
String data = StreamTool.decodeStream(in);
Message msg = Message.obtain();
msg.what=SUCCESS;
msg.obj=data;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
e.printStackTrace();
}
};
}.start();
}
}
StreamTool.java:
package com.lcz.newsclient.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamTool {
public static String decodeStream(InputStream in) throws Exception {
// TODO Auto-generated method stub
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int len=0;
byte[] buf=new byte[1024];
while((len=in.read(buf))>0){
baos.write(buf,0,len);
}
return baos.toString();
}
}
layout中activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/qq"
android:layout_gravity="center_horizontal"/>
<EditText
android:id="@+id/ed_number"
android:hint="请输入qq号码"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/ed_pwd"
android:hint="请输入qq密码"
android:inputType="textPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/login"
android:text="登录"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/login_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
同样的添加权限AndroidMainfest.xml中:
<uses-permission android:name="android.permission.INTERNET"/>
服务器端MyEclipse中(这里是新建了一个web project,然后又建立了一个Servlet)
LoginServlet.java 主要是判断传来的账户和密码是否正确
源码:LoginServlet.java源码:
package com.lcz.login;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//GET方式要手动解决论码
String number=request.getParameter("number");
number=new String(number.getBytes("iso8859-1"),"UTF-8");
String pwd=request.getParameter("pwd");
System.out.println("number:"+number+",pwd:"+pwd);
//如果qq号码5201314和密码520lcz
if("5201314".equals(number)&&"520lcz".equals(pwd)){
//如果进来,则正确
response.getWriter().print("login success");
}else{
response.getWriter().print("login falied");
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String number=request.getParameter("number");
number=new String(number.getBytes("iso8859-1"),"UTF-8");
String pwd=request.getParameter("pwd");
System.out.println("number:"+number+",pwd:"+pwd);
//如果qq号码5201314和密码520lcz
if("5201314".equals(number)&&"520lcz".equals(pwd)){
//如果进来,则正确
response.getWriter().print("login success");
}else{
response.getWriter().print("login falied");
}
}
}
这里还需要将这个Web工程添加到服务器中
注意这里的Tomcat服务器是我添加的我本机上的服务器,在window下的preference中可以添加tomcat服务器,如下图
添加好tomcat服务器之后,tomcat服务器右键选择add deployment
之后出现下方图所示,在Project中选择自己的项目,确定就行,这里因为我已经挂载上去了,所以没显示那个web项目
之后还是右键tomcat服务器,启动tomcat服务器,如果再console控制台出现最后一行,表示启动成功
正确的将项目添加到tomcat如下图
三、连接测试
(1)电脑跟真机应该处于同一局域网内,这里我采用的是用手机开热点的方式。
(2)获取电脑的ip地址,cmd命令行下输入ipconfig来知晓
(3)防火墙打开8080端口,具体开启可参考点击打开链接
(4)运行即可。
post方法来传递数据
这里post方法只是在Eclipse中MainActivity中代码中有所不同,下面给出代码
package com.lcz.login_in;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import com.lcz.newsclient.utils.StreamTool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
private Button login;
private EditText ed_number;
private EditText ed_pwd;
private TextView tv_status;
private String path="http://192.168.43.125:8080/Web/servlet/login";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button) findViewById(R.id.login);
login.setOnClickListener(this);
ed_number=(EditText) findViewById(R.id.ed_number);
ed_pwd=(EditText) findViewById(R.id.ed_pwd);
tv_status=(TextView) findViewById(R.id.login_status);
}
private Handler mHandler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
String data=(String) msg.obj;
tv_status.setText(data);
break;
case ERROR:
Toast.makeText(MainActivity.this, "连接错误", 0).show();
break;
default:
break;
}
};
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//获得qq号码和密码,然后登录
final String number = ed_number.getText().toString().trim();
final String pwd=ed_pwd.getText().toString().trim();
if(TextUtils.isEmpty(number)||(TextUtils.isEmpty(pwd))){
Toast.makeText(this, "号码或密码不能为空", 0).show();
return;
}
//走到这里,说明qq号码和密码都输入了,然后需要连接网络
new Thread(){
public void run() {
try {
//path=path+"number="+URLEncoder.encode(number,"UTF-8")+"&pwd="+URLEncoder.encode(pwd,"UTF-8");
URL url=new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//准备数据
String data="number="+URLEncoder.encode(number,"UTF-8")+"&pwd="+URLEncoder.encode(pwd,"UTF-8");
conn.setRequestProperty("Content-Length", data.length()+"");
//这个地方表示告诉了 加了一个标志,要给服务器写数据了
conn.setDoOutput(true);
conn.getOutputStream().write(data.getBytes());
int code = conn.getResponseCode();
if(code==200){
InputStream in = conn.getInputStream();
//流转换为字符串
String data2 = StreamTool.decodeStream(in);
Message msg = Message.obtain();
msg.what=SUCCESS;
msg.obj=data2;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
Message msg = Message.obtain();
msg.what=ERROR;
mHandler.sendMessage(msg);
e.printStackTrace();
}
};
}.start();
}
}