您的位置:首页 > 理论基础 > 计算机网络

URL和HTTPClient与服务器的连接

2015-08-12 20:45 316 查看

服务器

在这里用到了一个Apache来建立一个服务器,并与数据库建立连接,使得客户端可以通过服务器去验证并登录。

package com.lingzhuo.tomcat;

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 {
// TODO Auto-generated method stub
String username=request.getParameter("username");
String password=request.getParameter("password");
String s="";
Connection conn=SqlManger.newInstance().getConnection();
String select="select * from user where name=? and password=?";
try {
PreparedStatement prepare=conn.prepareStatement(select);
prepare.setString(1, username);
prepare.setString(2, password);
ResultSet set= prepare.executeQuery();
set.last();
int num=set.getRow();
if(num==1){
s="登录成功";
}else{
s="用户名或密码错误";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//String name=Encoding.doEncoding(username);
System.out.println("用户名:"+username+"  密码:"+password);
response.setHeader("Content-type", "text/heml;charset=UTF-8");
response.getWriter().append(username+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);
}

}


package com.lingzhuo.tomcat;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlManger {
private static SqlManger manger;
private Connection connection;
public Connection getConnection() {
return connection;
}
public static synchronized SqlManger newInstance(){
if(manger==null){
manger=new SqlManger();
}
return manger;
}
private SqlManger(){
String Driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/clazz";
String user="root";
String password="1639189";
try {
Class.forName(Driver);
connection=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


URL

url通过doget方法与服务器建立连接并传输数据

package com.lingzhuo.http;

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.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 UrlConnectionGet extends JFrame {

private JPanel contentPane;

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

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

JButton btnhttp = new JButton("启动http");
btnhttp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String urlString="http://localhost:8080/MyServiceTest/MyServerlet?username=zhangsan&password=123456";
try {
//获得url
URL url=new URL(urlString);
//url与服务器建立连接
URLConnection urlConnection=url.openConnection();
//将urlConnection强制造型为HttpURLConnection类型
HttpURLConnection httpConnection=(HttpURLConnection) urlConnection;
//设置请求方法
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");
//获取HTTP状态码
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 str=br.readLine();
while(str!=null){
System.out.println(str);
str=br.readLine();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(ConnectException e){
System.out.println("连接超时");
}catch(SocketTimeoutException e){
System.out.println("读取时间超时");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnhttp.setBounds(64, 29, 93, 23);
contentPane.add(btnhttp);
}
}


url通过dopost方法与服务器建立连接并传输数据

package com.lingzhuo.http;

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.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 UrlConnectionPost extends JFrame {

private JPanel contentPane;

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

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

JButton btnurl = new JButton("启动URL客户端");
btnurl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String urlString="http://localhost:8080/MyServiceTest/MyServerlet";
try {
URL url=new URL(urlString);
HttpURLConnection httpConnection=(HttpURLConnection) url.openConnection();

//设置连接超时时间
httpConnection.setConnectTimeout(3000);
//设置读取超时时间
httpConnection.setReadTimeout(3000);
//设置编码格式和接收数据类型
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
//设置可以接收序列化的java对象
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求方法
httpConnection.setRequestMethod("POST");
//httpConnection.setDoInput(true);
//
httpConnection.setDoOutput(true);
//post不允许使用缓存
httpConnection.setUseCaches(false);
String info="username=zhangsan&password=123";
httpConnection.getOutputStream().write(info.getBytes());
//获取HTTP状态码
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 str=br.readLine();
while(str!=null){
System.out.println(str);
str=br.readLine();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ConnectException e){
System.out.println("连接超时");
}catch(SocketTimeoutException e){
System.out.println("读取时间超时");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
btnurl.setBounds(27, 21, 157, 23);
contentPane.add(btnurl);
}

}


HTTPClient

HttpClient通过doget方法与服务器建立连接并传输数据

package com.lingzhuo.http;

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.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 HttpClientGet extends JFrame {

private JPanel contentPane;

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

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

JButton btnNewButton = new JButton("HttpClient启动");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String url="http://localhost:8080/MyServiceTest/MyServerlet?username=zhangsan&password=123";
//生成client的builder
HttpClientBuilder builder=HttpClientBuilder.create();
//连接超时时间
builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
//生成client
HttpClient client=builder.build();
//设置get方法
HttpGet get=new HttpGet(url);
//设置服务器接收数据后的读取方式为utf-8
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
try {
//执行get方法后得到服务器返回的所有数据都在response中
HttpResponse response=client.execute(get);
//httpclient访问服务器返回的表头,包含http状态码
StatusLine status=response.getStatusLine();
int code=status.getStatusCode();
if(code==HttpURLConnection.HTTP_OK){
//得到数据的实体
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=br.readLine();
while(str!=null){
System.out.println(str);
str=br.readLine();
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
});
btnNewButton.setBounds(34, 44, 192, 32);
contentPane.add(btnNewButton);
}
}


HttpClient通过dopost方法与服务器建立连接并传输数据

package com.lingzhuo.http;

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.StatusLine;
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 HttpClientPost extends JFrame {

private JPanel contentPane;

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

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

JButton btnHttpclientpost = new JButton("HttpClientPost启动");
btnHttpclientpost.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String url="http://localhost:8080/MyServiceTest/MyServerlet";
HttpClientBuilder builder=HttpClientBuilder.create();
HttpClient client=builder.build();
builder.setConnectionTimeToLive(3000,TimeUnit.MILLISECONDS);
//设置post方法
HttpPost post=new HttpPost(url);
//对提交到服务器的信息进行封装
NameValuePair pair1=new BasicNameValuePair("username", "zhangsan");
NameValuePair pair2=new BasicNameValuePair("password", "123");
ArrayList<NameValuePair> pair=new ArrayList<>();
pair.add(pair1);
pair.add(pair2);
try {
//把封装好的信息以utf-8的方式发送
post.setEntity(new UrlEncodedFormEntity(pair,"utf-8"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//执行post方法,response中为服务器返回的信息
HttpResponse response=client.execute(post);
StatusLine status=response.getStatusLine();
int code =status.getStatusCode();
if(code==HttpURLConnection.HTTP_OK){
HttpEntity entity=response.getEntity();
InputStream is=entity.getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=br.readLine();
while(str!=null){
System.out.println(str);
str=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();
}
}
});
btnHttpclientpost.setBounds(58, 39, 184, 34);
contentPane.add(btnHttpclientpost);
}

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