WebServer

WebServer

先安装相关插件,导入相应的jar包
相关插件:apache-tomcat-7.0.63-windows-x64
tomcatPluginV3
具体操作参照视频、或搜索相关教程

创建Serverlet用来给前端提供数据,服务器的编码规则与网页不同,需要相应转换。

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a>你好,谢谢</a>
</body>
</html>

编码规则转换

package com.lingzhuo.testWeb;

import java.io.UnsupportedEncodingException;

public class Encoding {
    public static String doEncoding(String string){
        try {
            byte[] array = string.getBytes("ISO-8859-1");
            string = new String (array,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return string;
    }
}

服务器发送数据

package com.lingzhuo.testWeb;

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;

/**
 * Servlet implementation class MyTestServlet
 */
@WebServlet("/MyTestServlet")
public class MyTestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyTestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        username = Encoding.doEncoding(username);
        String s = "";
        System.out.println("用户名:"+username+"\t密码:"+password);
        /**
         * 与服务器建立连接
         */
        try {
            Connection conn = SQLManager.newInstance().getConn();
            PreparedStatement state = conn.prepareStatement("select * from user where user_name=? and password=?");
            state.setString(1, username);
            state.setString(2, password);
            ResultSet set = state.executeQuery();
            set.last();
            int num = set.getRow();
            if(num==1){
                s = "登录成功";
            }else{
                s = "用户名或密码错误";
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //让浏览器以utf-8编码格式解析
        response.getWriter().append(s);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

客户端与服务器建立连接的方法

URL connection

package com.lingzhuo.test;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class UrlConnectionTest extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UrlConnectionTest frame = new UrlConnectionTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public UrlConnectionTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 622, 478);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("doGet方法测试");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String  urlString="http://localhost:8080/MyServiceTest/MyTestServerlet?username=zhangsan&password=123456";
                //直接跟在url后是doGet方法
                try {
                    URL url=new URL(urlString);//生成URL
                    URLConnection connect=url.openConnection();//打开url连接
                    //强制造型成httpUrlConnection
                    HttpURLConnection  httpConnection=(HttpURLConnection) connect;
                    //设置请求方法
                    httpConnection.setRequestMethod("GET");
                    //设置连接超时的时间
                    httpConnection.setConnectTimeout(3000);
                    //读取时间超时
                    httpConnection.setReadTimeout(3000);
                    //设置编码格式
                    // 设置接受的数据类型
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置可以接受序列化的java对象
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    int code=httpConnection.getResponseCode();
                    System.out.println(" HTTP 状态码"+code);
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream is=httpConnection.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch(SocketTimeoutException e){
                    System.out.println("网络连接超时");
//                  e.printStackTrace();
                }catch(ConnectException e){
                    System.out.println("服务器拒绝连接");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(196, 110, 198, 193);
        contentPane.add(btnNewButton);
    }
}
package com.lingzhuo.test;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.awt.event.ActionEvent;

public class DoPostTest extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    DoPostTest frame = new DoPostTest();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public DoPostTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 784, 635);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String urlString = "http://localhost:8080/MyServiceTest/MyTestServerlet";
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
                    //设置连接超时的时间
                    httpConnection.setConnectTimeout(30000);
                    //读取时间超时
                    httpConnection.setReadTimeout(30000);
                    //设置编码格式
                    // 设置接受的数据类型
                    httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置可以接受序列化的java对象
                    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //设置请求方法
                    httpConnection.setRequestMethod("POST");
//                  httpConnection.setDoInput(true);//设置可以读取服务器返回的内容,默认为true
                    //设置客户端可以给服务器提交数据,默认是false的。post方法必须设置为true
                    httpConnection.setDoOutput(true);
                    //post方法不允许使用缓存
                    httpConnection.setUseCaches(false);
                    String params="username=zhangsan&password=123456";
                    httpConnection.getOutputStream().write(params.getBytes());
                    int code=httpConnection.getResponseCode();
                    System.out.println(code);
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream  is=httpConnection.getInputStream();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(228, 130, 293, 278);
        contentPane.add(btnNewButton);
    }
}

HttpClientDoGet方法

package com.lingzhuo.test;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpClientDoGet extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HttpClientDoGet frame = new HttpClientDoGet();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public HttpClientDoGet() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 683, 516);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("HttpClientDoGet");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlString="http://localhost:8080/MyServiceTest/MyTestServerlet?username=zhangsan&password=123456";
                HttpClientBuilder builder=HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                //生成client的buidler
                HttpClient client=builder.build();//生成client
                HttpGet get=new HttpGet(urlString);//设置为get方法
                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                //设置服务器接收后数据的读取方式为utf8
                try {
                    HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                    StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                    int code=statusLine.getStatusCode();//得到状态码
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity=response.getEntity();//得到数据的实体
                        InputStream is=entity.getContent();//得到输入流
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(221, 150, 218, 169);
        contentPane.add(btnNewButton);
    }

}

HttpClientDoPost方法

package com.lingzhuo.test;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpClientDoPost extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HttpClientDoPost frame = new HttpClientDoPost();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public HttpClientDoPost() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 810, 665);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("HttpClientDoPost");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String url="http://192.168.0.30:8080/MyServiceTest/MyTestServerlet";
                HttpClientBuilder builder=HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient client=builder.build();
                HttpPost post=new HttpPost(url);
                NameValuePair pair1=new BasicNameValuePair("username", "张三");
                NameValuePair pair2=new BasicNameValuePair("password", "123456");
                ArrayList<NameValuePair> params=new ArrayList<>();
                params.add(pair1);
                params.add(pair2);
                try {
                    post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    HttpResponse response=client.execute(post);
                    int code=response.getStatusLine().getStatusCode();
                    if(code==200){
                        HttpEntity entity=response.getEntity();
                        InputStream is=entity.getContent();
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        btnNewButton.setBounds(247, 193, 305, 199);
        contentPane.add(btnNewButton);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值