Web服务器的建立
HttpUrlConnection
HttpClient
package com.baidu.test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 MyServerLet
*/
@WebServlet("/MyServerLet")
public class MyServerLet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServerLet() {
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"); //从网页中得到关键字username后面的内容
String passwrod=request.getParameter("password"); //从网页中得到关键字password后面的内容
username=EnCoding.doEncoding(username); //将username的编码个是转换为utf-8的格式
System.out.println("用户名:"+username+"密码为:"+passwrod);
String s="";
Connection conn=SQLManger.newInstance().getConnection(); //连接数据库
try {
//创建一个preparedStatement对象,从数据库中筛选username和password数据对
PreparedStatement state=conn.prepareStatement("select * from user where user_name=? and password=?");
state.setString(1, username);
state.setString(2, passwrod);
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();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
response.setHeader("Content-type", "text/html;charset=UTF-8");
// 让浏览器以UTF-8编码格式解析
response.getWriter().append(s);
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.baidu.test;
import java.io.UnsupportedEncodingException;
public class EnCoding {
/***
* 这个方法是用来将ISO-8859-1类型的字符转变为UTF-8类型的字符
* @param str 传入ISO-8859-1类型的字符串
* @return 返回UTF-8类型的字符
*/
public static String doEncoding(String str){
try {
byte[] array=str.getBytes("ISO-8859-1"); //将传入的字符串转变为字节类型
str=new String(array, "UTF-8"); //将字节类型的数据转换为字符串类型
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
}
package com.baidu.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLManger {
private Connection connection;
public Connection getConnection() {
return connection;
}
/**
* 单例设计模式
*/
private static SQLManger manger;
public static synchronized SQLManger newInstance(){
if (manger==null) {
manger=new SQLManger();
}
return manger;
}
/***
* 该方法是用来连接指定url的数据库
* localhost可以写成别人的ip地址,这样就能连接到别人的数据库
*/
private SQLManger (){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/clazz";
String user="root";
String password="123456";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
HttpUrlConnection是sun封装成的网络连接,分的比较细,使用起来比较麻烦doGet 直接连接在URL后边 是显示的
doPost 是隐式的提交,一般用于表格的提交
HttpClient 是Apache使用HttpUrlConnection封装的类,接口比较确定,使用起来比较方便
HttpUrlConnection和HttpClient 的程序例子
package com.baidu.url;
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.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JLabel;
public class URLConnectionFinalText extends JFrame {
private JPanel contentPane;
private JTextField textFieldUserName;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
URLConnectionFinalText frame = new URLConnectionFinalText();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public URLConnectionFinalText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 398, 433);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("DoPost");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName=textFieldUserName.getText();
char[] pass=passwordField.getPassword();
String passWord=new String(pass);
String params="username="+userName+"&password="+passWord;
HTTPSetDoPost doPost=new HTTPSetDoPost();
doPost.HTTPDoPost(params);
}
});
btnNewButton.setBounds(190, 193, 166, 52);
contentPane.add(btnNewButton);
JButton button = new JButton("退出");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
button.setBounds(10, 363, 362, 32);
contentPane.add(button);
textFieldUserName = new JTextField();
textFieldUserName.setBounds(122, 35, 176, 42);
contentPane.add(textFieldUserName);
textFieldUserName.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(122, 111, 176, 42);
contentPane.add(passwordField);
JLabel label = new JLabel("用户名");
label.setBounds(28, 48, 54, 15);
contentPane.add(label);
JLabel label_1 = new JLabel("密码");
label_1.setBounds(28, 124, 54, 15);
contentPane.add(label_1);
JButton btnDoget = new JButton("DoGet");
btnDoget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName=textFieldUserName.getText();
char[] pass=passwordField.getPassword();
String passWord=new String(pass);
String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet?username="+userName+"&password="+passWord;
HTTPSetDoGet httpSetDoGet=new HTTPSetDoGet();
httpSetDoGet.doGet(urlString);
}
});
btnDoget.setBounds(10, 194, 155, 50);
contentPane.add(btnDoget);
JButton btnHttpclientdoget = new JButton("HTTPClientDoGet");
btnHttpclientdoget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName=textFieldUserName.getText();
char[] pass=passwordField.getPassword();
String passWord=new String(pass);
String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet?username="+userName+"&password="+passWord;
HTTPClientDoGet httpClientDoGet=new HTTPClientDoGet();
httpClientDoGet.doGet(urlString);
}
});
btnHttpclientdoget.setBounds(10, 285, 155, 52);
contentPane.add(btnHttpclientdoget);
JButton btnHttpclientdopost = new JButton("HTTPClientDoPost");
btnHttpclientdopost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userName=textFieldUserName.getText();
char[] pass=passwordField.getPassword();
String passWord=new String(pass);
HTTPClientDoPost httpClientDoPost=new HTTPClientDoPost();
httpClientDoPost.doPost(userName, passWord);
}
});
btnHttpclientdopost.setBounds(184, 285, 172, 52);
contentPane.add(btnHttpclientdopost);
}
}
package com.baidu.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
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.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HTTPClientDoGet {
/***
* 该方法是链接URL服务器利用,并用GET方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8
* 执行GET方法得到服务器的返回的所有数据都在response中
* @param urlString 传入包含用户名和密码的url
*/
public void doGet(String urlString){
// String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet?username=ni&password=123456";
HttpClientBuilder bulider=HttpClientBuilder.create(); //由于不能直接创建HttpClientBuilder所以利用他的方法来创建这个实例
HttpClient client=bulider.build(); //利用build方法创建一个Httpclient实例(生成client)
HttpGet get=new HttpGet(urlString); //生成url(设置为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 e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baidu.url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
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;
public class HTTPClientDoPost {
/***
* 该方法是链接URL服务器利用,并用post方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8
* 执行post方法得到服务器的返回的所有数据都在response中
* @param userName 传入用户名
* @param passWord 传入密码
*/
public void doPost(String userName,String passWord){
String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet";
HttpClientBuilder builder=HttpClientBuilder.create(); //创建HttpClientBuilder
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); //设置链接超时
HttpClient client=builder.build(); //创建Client
HttpPost post=new HttpPost(urlString); //设置为Post方法
NameValuePair pair=new BasicNameValuePair("username" ,userName); //
NameValuePair pair2=new BasicNameValuePair("password", passWord); //
ArrayList<NameValuePair> params=new ArrayList<>(); //创建ArrayList数组
params.add(pair); //添加元素
params.add(pair2); //添加元素
try {
post.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); //创建一个实体,将ArrayList封装为UTF-8的类型
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置服务器接收数据后的读取方式为UTF-8
HttpResponse response=client.execute(post); //执行post方法得到服务器的返回的所有数据都在response中
int code=response.getStatusLine().getStatusCode(); //httpClient访问服务器返回的表头,包含http状态码,并得到状态码
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 (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.baidu.url;
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;
public class HTTPSetDoGet {
/***
* 该方法是链接URL服务器利用,并用GET方法向服务器提交数据,设设置服务器接收数据后的读取方式为UTF-8
* 返回的数据显示到客户端上
* @param urlString 传入带有用户名和密码的URL
*/
public void doGet(String urlString){
// String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet?username=ni&password=123456";
try {
URL url=new URL(urlString); //生成URL链接
URLConnection urlConnection=url.openConnection(); //打开URL链接
HttpURLConnection httpConnection=(HttpURLConnection) urlConnection; //强制造型成为HttpURLConnection
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(); //获取HTTP状态码
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 e1) {
e1.printStackTrace();
}catch(SocketTimeoutException e1){
System.out.println("链接超时");
} catch(ConnectException e1){
System.out.println("服务器拒绝链接");
}catch (IOException e1) {
e1.printStackTrace();
}
}
}
package com.baidu.url;
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;
public class HTTPSetDoPost {
/***
* 该方法是打开URL连接到服务器,设置请求方式为POST,设置可读服务器返回的内容(默认为True)
* 设置客户端可以向服务器提交数据,默认是false,post方法必须设置为true
* 设置post方法不允许用缓存
* @param params 传入字符串中包含用户名和密码
*/
public void HTTPDoPost(String params){
String urlString="http://localhost:8080/ElevenAugMyServer/MyServerLet";
try {
URL url=new URL(urlString); //生成URL链接
URLConnection urlConnection=url.openConnection(); //打开URL链接
HttpURLConnection httpConnection=(HttpURLConnection)urlConnection; //强制造型成为HttpURLConnection
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);
httpConnection.setUseCaches(false); //post方法不允许用缓存
httpConnection.getOutputStream().write(params.getBytes());
int code=httpConnection.getResponseCode(); //获取HTTP状态码
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 e1) {
e1.printStackTrace();
}catch(SocketTimeoutException e1){
System.out.println("链接超时");
} catch(ConnectException e1){
System.out.println("服务器拒绝链接");
}catch (IOException e1) {
e1.printStackTrace();
}
}
}