java web和Android第一次交互(登录)

来源:互联网 发布:pscs3软件百度云 编辑:程序博客网 时间:2024/06/08 06:57

一.开发环境

Android代码用eclipse开发   javaweb用Ide开发

二.Android代码

  新建Android项目

package com.example.testlogin;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {


public static String Home="http://192.168.1.45:8080/Test/login";//换成自己的地址
private static TextView tv;
private TextView top2;
public static Handler mHandler=new Handler(){
public void handleMessage(android.os.Message msg) {
tv.setText((String)msg.obj);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText user=(EditText)findViewById(R.id.edittext);
final EditText pass=(EditText)findViewById(R.id.edittext2);
tv=(TextView)findViewById(R.id.top);
top2=(TextView)findViewById(R.id.top2);
top2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
loginByPost(user.getText().toString(),pass.getText().toString()); //测试帐号123  密码123

}
}).start();
}
});

}


public static String loginByPost(String username,String password){    
       try {
           URL url = new URL(Home);
           HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
           conn.setConnectTimeout(5000);
           conn.setRequestMethod("POST");
           String data = "username="+URLEncoder.encode(username)+"&password="
                   +URLEncoder.encode(password);
           System.out.println(data);
           conn.setRequestProperty("Content=Type", "application/x-wwww-form-urlencoded");
           conn.setRequestProperty("Content-length", data.length()+"");
           conn.setRequestProperty("Accept-Charset", "utf-8");
           conn.setRequestProperty("contentType", "utf-8");
           conn.setDoOutput(true);
           OutputStream os = conn.getOutputStream();
           os.write(data.getBytes());
           int code = conn.getResponseCode();
           System.out.println(code);
           if (code == 200) {
               InputStream is = conn.getInputStream();
               String text =URLDecoder.decode( ReadInputStream(is), "UTF-8");
               Message msg=new Message();
               msg.obj=text;
               mHandler.sendMessage(msg);
               return text;
           }else {
               return null;
           }
           
       } catch (MalformedURLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           System.out.println("111111");
       } catch (ProtocolException e) {
           System.out.println("222222");
           e.printStackTrace();
       } catch (IOException e) {
           System.out.println("33333");
           e.printStackTrace();
       }
       return null;
   }

//读取输入流

public static String ReadInputStream(InputStream is) {
       try {
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           int len = 0;
           byte[] buffer = new byte[1024];
           while ((len = is.read(buffer)) != -1) {
               baos.write(buffer, 0, len);
           }
           is.close();
           baos.close();
           byte[] result = baos.toByteArray();
           return new String(result);


       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
           return "将输入流转化为字符串失败";
       }
   }
}

布局文件

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@android:color/white"
    tools:context="com.example.testlogin.MainActivity" >


    <TextView
        android:id="@+id/top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <EditText 
        android:layout_below="@id/top"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:id="@+id/edittext"/>
    <EditText 
           android:layout_width="100dp"
        android:layout_height="50dp"
            android:layout_below="@id/edittext"
        android:id="@+id/edittext2"/>
    <TextView
        android:id="@+id/top2"
        android:layout_below="@id/edittext2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />


</RelativeLayout>

主配置文件 添加联网权限 

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

三.服务端   配置tomcat  

1.   新建web项目,在web下新建libs包     导入servlet-api.jar 

2.配置web.xml

<servlet>    <servlet-name>login</servlet-name>    <servlet-class>com.marven.web.Login</servlet-class></servlet><servlet-mapping>    <servlet-name>login</servlet-name>    <url-pattern>/login</url-pattern></servlet-mapping>
3.Login代码

package com.marven.web;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.swing.*;import java.awt.*;import java.io.IOException;/** * Created by Marven on 2016/8/2. */public class Login extends HttpServlet{    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("UTF-8");        String username = request.getParameter("username");        String password = request.getParameter("password");        if ("123".equals(username)&&"123".equals(password)) {            System.out.println("登录成功");            response.getOutputStream().write("登录成功".getBytes("utf-8"));            System.out.println("返回的数据:" + "登录成功".getBytes("utf-8"));        }else {            System.out.println("登录失败");            response.getOutputStream().write("登录失败".getBytes("utf-8"));        }    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setCharacterEncoding("UTF-8");        response.setHeader("content-type", "text/html;charset=UTF-8");        doGet(request, response);    }}
完毕     。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

0 0
原创粉丝点击