一、get方式通信

1、Web端

1)建立一个Servlet命名为TestAppServlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/TestAppServlet")
public class TestAppServlet extends HttpServlet {

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("接收到客户端的访问:");
        System.out.println(request.getParameter("param"));
        response.getOutputStream().print("Server data");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

2)在webContent/WEB-INF/web.xml文件中注册TestAppServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>TestAppServlet</servlet-name>
    <servlet-class>com.zcn.servlet.TestAppServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestAppServlet</servlet-name>
    <url-pattern>/servlet/TestAppServlet</url-pattern>
  </servlet-mapping>
</web-app>

2、Android端

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread thread = new Thread(){
            @Override
            public void run() {
                initView();
            }
        };
        thread.start();

    }

    private void initView() {
        System.out.println("Chunna==开始连接");
        String strUrl="http://192.168.2.169:8080/TestTomcat/servlet/TestAppServlet?param=helloWorld";//地址要写成跑web程序端的地址,且如果web端不是在服务器上还要保证手机端和web端在同一局域网下
        URL url = null;
        try{
            url=new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            InputStreamReader in = new InputStreamReader(urlConnection.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String result = "";
            String readLine = null;
            while((readLine=br.readLine())!=null){
                System.out.println("Chunna==不为空");
                result+=readLine;
            }
            in.close();
            urlConnection.disconnect();
            System.out.println("Chunna==结果"+result);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二、post方式通信

1、web端不变

2、Android端

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread thread = new Thread(){
            @Override
            public void run() {
                //initView();
                doPost();
            }
        };
        thread.start();

    }

    private void doPost(){
        String strUrl="http://192.168.2.169:8080/TestTomcat/servlet/TestAppServlet";//地址要写成跑web程序端的地址,且如果web端不是在服务器上还要保证手机端和web端在同一局域网下
        URL url = null;
        try {
            url=new URL(strUrl);
            HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
            urlConn.setDoInput(true);//设置输入流采用字节流
            urlConn.setDoOutput(true);//设置输出流采用字节流
            urlConn.setRequestMethod("POST");//设置以post形式
            urlConn.setUseCaches(false);//设置缓存
            urlConn.setRequestProperty("Content_Type", "application/x-www-form-urlencoded");//设置meta参数
            urlConn.addRequestProperty("Charset", "utf-8");//设置编码格式为utf-8
            System.out.println("Chunna==开始连接");
            urlConn.connect();

            //发送数据
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.writeBytes("param="+ URLEncoder.encode("hello", "utf-8"));
            dos.flush();
            dos.close();

            //接收数据
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String result = "";
            String readLine=null;
            while((readLine=br.readLine())!=null){
                System.out.println("Chunna==不为空");
                result+=readLine;
            }
            br.close();
            urlConn.disconnect();
            System.out.println("Chunna==结果"+result);
        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐