1. 程式人生 > >java web和Android第一次互動(登入)

java web和Android第一次互動(登入)

一.開發環境

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);

    }
}

完畢     。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。