您的位置:首页 > 运维架构

第十八天 doGet和doPost

2015-08-12 21:13 495 查看

doGet 和doPost

doGet 直接连接在url后边 是显式的

doPost 隐式的,比较安全

HttpUrlConnection 是sun封装成的网络连接

HttpClient 是apache使用HttpUrlConnection封装的类

Encoding(JavaEE项目)

package com.java.test;
import java.io.UnsupportedEncodingException;
public class Encoding {
public static String doEncoing(String string) {
try {
if(string ==null){
return null;
}
byte[] array=string.getBytes("ISO-8859-1");
string=new String(array,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
}


SQLManager(JavaEE项目)

package com.java.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLManager {
private Connection connection;
public Connection getConnection() {
return connection;
}
private static SQLManager manager;
public static SQLManager newInstance(){
if(manager==null){
manager=new SQLManager();
}
return manager;
}
private SQLManager(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/class";
String user="root";
String password="123456";
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, user, password);

} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}


ServLet(JavaEE项目)

package com.java.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 MyTestServlet
*/
@WebServlet("/MyTestServlet")
public class MyTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyTestServlet() {
super();
}
/**
* @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.doEncoing(userName);//在httpclient的dopost中,这一句不写
System.out.println(""+userName+","+password+"");
String s="得到的用户名为:"+userName+" 密码为:"+password;
Connection con=SQLManager.newInstance().getConnection();
try {
PreparedStatement state=con.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){
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().append(s);

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

doGet(request, response);
}
}


HttpUrlConnection的doGet(Java项目)

package com.java.test;
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.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.awt.event.ActionEvent;

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, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnDoget = new JButton("doGet测试");
btnDoget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlString="http://localhost:8080/JavaEE/MyTestServlet?username=zhangsan&password=123456";
try {
URL url=new URL(urlString);//生成URL
URLConnection connection=url.openConnection();//打开URL连接
HttpURLConnection http=(HttpURLConnection) connection;//强制造型
http.setRequestMethod("GET");//设置请求方法

//设置编码格式                http.setRequestProperty("Accept-Charset", "utf-8");//接受的数据类型
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置可以接受的序列化的java对象
http.setConnectTimeout(3000);//请求连接的时间
http.setReadTimeout(3000);
int code=http.getResponseCode();
System.out.println("HTTP状态码"+code);
if(code==http.HTTP_OK){//服务器OK
InputStream is=http.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader (is));
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
}  catch(SocketTimeoutException e1){
System.out.println("连接超时");
}catch(ConnectException e1){
System.out.println("服务器拒绝连接");
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnDoget.setBounds(138, 108, 102, 47);
contentPane.add(btnDoget);
}
}


HttpUrlConnection的doPost(Java项目)

package com.java.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 javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class URLConnection extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
URLConnection frame = new URLConnection();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public URLConnection() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnPost = new JButton("POST测试");
btnPost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlString="http://localhost:8080/JavaEE/MyTestServlet";
try {
URL url=new URL(urlString);
HttpURLConnection http=(HttpURLConnection) url.openConnection();
http.setRequestProperty("Accept-Charset", "utf-8");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestMethod("POST");
http.setDoInput(true);//设置可以读取服务器返回的内容,默认为true
http.setDoOutput(true);//设置客户端可以给服务器提交数据,默认为false,必须设为true
http.setUseCaches(false);//Post方法不允许使用缓存
String s="username=lisi&password=123456";
http.getOutputStream().write(s.getBytes());
http.setConnectTimeout(3000);
http.setReadTimeout(3000);
int code=http.getResponseCode();
System.out.println("HTTP状态码"+code);
if(code==http.HTTP_OK){
InputStream is=http.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader (is));
String line=br.readLine();
while(line!=null){
System.out.println(line);
line=br.readLine();
}
}
} catch(SocketTimeoutException e1){
System.out.println("连接超时");
}catch(ConnectException e1){
System.out.println("服务器拒绝连接");
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnPost.setBounds(122, 107, 93, 39);
contentPane.add(btnPost);
}
}


HttpClient的doGet

package com.java.test;
import java.awt.EventQueue;
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.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
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.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;

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, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton button = new JButton("测试");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlString="http://localhost:8080/JavaEE/MyTestServlet?username=lisi&password=123456";
HttpClientBuilder builder=HttpClientBuilder.create();//生成client的builder
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();//生成client
HttpGet get=new HttpGet(urlString);//设置为get方法
//设置服务器接收后数据的读取方式为utf-8
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
try {
HttpResponse response = client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
int code=statusLine.getStatusCode();//得到状态码
System.out.println("状态码为:"+code);
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) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setBounds(127, 110, 93, 45);
contentPane.add(button);
}
}


HttpClient的doPost

package com.java.test;
import java.awt.BorderLayout;
import java.awt.EventQueue;
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 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.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.awt.event.ActionEvent;

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, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JButton btnDopost = new JButton("DoPost");
btnDopost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String urlString="http://localhost:8080/JavaEE/MyTestServlet";
HttpClientBuilder builder=HttpClientBuilder.create();
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
HttpClient client=builder.build();
HttpPost post=new HttpPost(urlString);
NameValuePair pair1=new BasicNameValuePair("username","张三");
NameValuePair pair2=new BasicNameValuePair("password","1234");
ArrayList<NameValuePair> list=new ArrayList<>();
list.add(pair1);
list.add(pair2);
try {
post.setEntity(new UrlEncodedFormEntity(list, "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==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 e1) {

e1.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

}
});
btnDopost.setBounds(124, 94, 124, 40);
contentPane.add(btnDopost);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: