Android客户端连接java的Servlet服务端

首先在Android studio创建一个项目

很简单的界面,你们要配置好Android的JDK和SDK。还有模拟器(不会去百度)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1">
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name" />

        <EditText
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:hint="@string/name1"/>

    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="@string/password" />
        <EditText
            android:id="@+id/password"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:hint="@string/password1"/>
    </LinearLayout>



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="登录" />


    </LinearLayout>

</LinearLayout>

 

这是他的java类的代码。里面有注解

package com.tao.test;

import
        android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    /**
     * 用于文本输入的名称和密码
     */
    private EditText name=null;
    private EditText password=null;

    private Button login=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * 得到输入文本对应的id名称
         */
        name=(EditText)this.findViewById(R.id.name);//对应名称
        password=(EditText)this.findViewById(R.id.password);//对应密码


        login=(Button)this.findViewById(R.id.login);//对应登录按钮

        /**
         * 登录按钮的单击事件
         */
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {//java的多线程这个必须有的
                        http(name.getText()+"",password.getText()+"");
                    }
                }).start();
            }
        });
    }
    public void http(String name,String password){
        HttpURLConnection huc=null;
        URL url=null;

        try {
            url=new URL("http://你的IP地址:8080/AndroidTest1/servlet/AndroidSer");
//连接的URL,点击电脑左下角,输入cmd,打开黑窗口,输入ipconfig回车,在里面找到你本地IP地址。不会去百度
            huc=(HttpURLConnection)url.openConnection();
            huc.setConnectTimeout(3000);
            huc.setUseCaches(false);
            huc.setInstanceFollowRedirects(true);
            huc.setReadTimeout(3000);
            huc.setDoInput(true);
            huc.setDoOutput(true);
            huc.setRequestMethod("POST");
            huc.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            huc.connect();

            JSONObject json=new JSONObject();
            json.put("name", URLEncoder.encode(name, "UTF-8"));//把name存储到JSON里面
            json.put("password", URLEncoder.encode(password, "UTF-8"));//把password存储到JSON里面
            String j=json.toString();//把json赋值给字符串


            OutputStream ups=huc.getOutputStream();//输出流
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(ups));//输出流转字符缓冲输出流
            bw.write(j);//输出字符串j
            bw.flush();
            ups.close();//关闭输出流
            bw.close();//关闭字符缓冲流
            huc.getResponseCode();//这个必须有,得到Http的应答器



        }catch (Exception e){
            e.printStackTrace();
        }finally {
            huc.disconnect();
        }
    }

}

 

然后打开Myeclipse,创建WEB项目。导入相应的jar包。这里你要有配置好java有关的所有配置(不会百度),还要有Tomcat服务器可以运行

 

创建Servlet类实现doGet和doPost方法

package Android;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;

import net.sf.json.JSONObject;

public class AndroidSer extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		System.out.println(request.getContentType());//得到客户端发送过来内容的类型
		System.out.println(request.getRemoteAddr());//得到客户端的IP地址
		BufferedReader bReader=new BufferedReader(new InputStreamReader(request.getInputStream()));
		String li=null;
		StringBuffer s=new StringBuffer();
		
		while((li=bReader.readLine())!=null){
			s.append(li);
		}
		bReader.close();
		System.out.println(s.toString());
		
		JSONObject jsonObject=JSONObject.fromObject(s.toString());
		
		String name = jsonObject.getString("name");//从json对象中得到相应key的值  
        String password = jsonObject.getString("password");  
        System.out.println("用户名2:"+name+",密码是2:"+password);
		
        /*
		response.setCharacterEncoding("UTF-8");  
        response.setContentType("application/json;charset=UTF-8");
        System.out.println("haohao044");
        String user1="root";
        String password1="123456";
        String driver="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://localhost:3306/android?userUnicode=true&characterEncoding=UTF-8";
        System.out.println("haohao055");
        Connection ct=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
        	Class.forName(driver);//加载驱动
        	ct=DriverManager.getConnection(url,user1,password1);
        	if(ct!=null){
        		System.out.println("连接成功");
        	}else{
        		System.out.println("连接失败");
        	}
        	String sql="select * from user";
        	ps=ct.prepareStatement(sql);
        	rs=ps.executeQuery();
        	List<String> list=new ArrayList<String>();
        	while (rs.next()) {
				list.add(rs.getString("name"));
				list.add(rs.getString("password"));
			}
        	for(int i=0;i<list.size();i++){
        		System.out.println(list.get(i));
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
			}
			if(ct!=null){
				try {
					ct.close();
				} catch (SQLException e2) {
					e2.printStackTrace();
				}
			}
		}*/
        
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

发布到Tomcat服务器上面,运行服务器。

在web.xml加入这个代码

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>AndroidService</servlet-name>
    <servlet-class>AndroidService</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>AndroidSer</servlet-name>
    <servlet-class>Android.AndroidSer</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>AndroidService</servlet-name>
    <url-pattern>/servlet/AndroidService</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>AndroidSer</servlet-name>
    <url-pattern>/servlet/AndroidSer</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

3.到Androidstudio运行模拟器,让你的项目在模拟器上运行。然后输入随便的名称和密码。点击登录

你就会在MyEclipse看到传过来的值了。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值