HttpURLConnection和HttpClient的用法
2015-08-12 19:51
543 查看
领卓教育培训第三十天
运行结果:
运行结果:
在服务器端加入连接数据库的代码:
创建管理数据库的类
运行结果:
将DoPost类中“username=张三”改为“username=zhangsan”,与数据库中用户名对应!
使用HttpClient发送请求、接收响应的一般步骤:
1. 创建生成client的builder,利用builder生成httpclient对象client
2. 创建请求实例,可以在创建实例的时候传入参数URL,也可以用setURI()方法指定URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 调用HttpClient对象client的execute()发送请求,该方法返回一个HttpResponse对象,该对象包含从服务器返回的所有数据。
4. 调用HttpResponse对象respons的getStatusLine()方法,得到表头,包含状态码。调用getEntity()方法,得到数据的实体,返回一个HttpEntity对象,调用该对象的getContent()方法,即可得到输入流!
运行结果:
运行结果:
HttpServlet
这里的servlet用上一篇博客中的作为web服务器!DoGet方法
使用httpservlet中的DoGet方法,与服务器进行数据交互![code]import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class DoGetTest { public static void main(String[] args) { try { //创建url对象 URL url= new URL("http://localhost:8080/MyTomcat/MyServletTest?username=张三&password=123456"); //得到URL连接 URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; //设置连接超时时间 httpConnection.setConnectTimeout(3000); //设置读取超时时间 httpConnection.setReadTimeout(3000); httpConnection.setRequestMethod("GET"); //设置编码格式 //设置接受的数据类型 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){ //接收到服务器返回的数据 BufferedReader br=new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String s = br.readLine(); while(s!=null){ System.out.println(s); s=br.readLine(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
DoPost方法
使用httpservlet中的DoPost方法,与服务器进行数据交互![code]import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class DoPostTest { public static void main(String[] args) { try { //创建url对象 URL url= new URL("http://localhost:8080/MyTomcat/MyServletTest"); //得到URL连接 URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) connection; //设置连接超时时间 httpConnection.setConnectTimeout(3000); //设置读取超时时间 httpConnection.setReadTimeout(20000); //设置编码格式 //设置接受的数据类型 httpConnection.setRequestProperty("Accept-charset", "UTF-8"); //设置可以接受序列号的java对象 httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConnection.setRequestMethod("POST"); //设置客户端可以给服务器提交数据,默认为false。POST方法必须设置为true httpConnection.setDoOutput(true); //POST方法不允许使用缓存 httpConnection.setUseCaches(false); String params="username=张三&password=123456"; httpConnection.getOutputStream().write(params.getBytes()); //得到HTTP状态码 int code = httpConnection.getResponseCode(); System.out.println("HTTP状态码:"+code); if(code==HttpURLConnection.HTTP_OK){ //接收到服务器返回的数据 BufferedReader br=new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); String s = br.readLine(); while(s!=null){ System.out.println(s); s=br.readLine(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
与数据库的交互
这里用doPost()方法进行一下测试在服务器端加入连接数据库的代码:
[code]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; import lingzhuo20150812.d2.SQLManager; /** * Servlet implementation class MyServletTest */ @WebServlet("/MyServletTest") public class MyServletTest extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServletTest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //使用浏览器提交数据默认的编码格式为ISO-8859-1 String username=request.getParameter("username"); String password=request.getParameter("password"); //将得到的数据转换为UTF-8编码格式 username=Encoding.doEncoding(username); password=Encoding.doEncoding(password); String s=""; try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } Connection connection=SQLManager.newInstance().getConnection(); try { PreparedStatement statement=connection.prepareStatement("select * from register where user_name=? and password=?"); statement.setString(1, username); statement.setString(2, password); ResultSet set=statement.executeQuery(); set.last(); int num=set.getRow(); if(num==1){ s="登录成功!"; }else{ s="用户名或密码错误"; } } catch (SQLException e) { e.printStackTrace(); } //让浏览器以UTF-8编码格式进行解析 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); } }
创建管理数据库的类
[code]import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class SQLManager { private Connection connection; public Connection getConnection() { return connection; } public void setConnection(Connection connection) { this.connection = connection; } private static SQLManager manager; public static synchronized SQLManager newInstance() { if (manager == null) { manager = new SQLManager(); } return manager; } private SQLManager() { try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "123456"); if (!connection.isClosed()) { Statement sql = connection.createStatement(); sql.execute( "CREATE TABLE if not exists register (ID int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,user_Name varchar(30) NOT NULL,password varchar(30) not null)"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
运行结果:
将DoPost类中“username=张三”改为“username=zhangsan”,与数据库中用户名对应!
HttpClient
客户端,服务器与数据库使用HttpClient发送请求、接收响应的一般步骤:
1. 创建生成client的builder,利用builder生成httpclient对象client
2. 创建请求实例,可以在创建实例的时候传入参数URL,也可以用setURI()方法指定URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 调用HttpClient对象client的execute()发送请求,该方法返回一个HttpResponse对象,该对象包含从服务器返回的所有数据。
4. 调用HttpResponse对象respons的getStatusLine()方法,得到表头,包含状态码。调用getEntity()方法,得到数据的实体,返回一个HttpEntity对象,调用该对象的getContent()方法,即可得到输入流!
GET请求
[code]import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; 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 HttpClientDoGetTest { public static void main(String[] args) { //创建生成client的builder HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build();//生成client //设置为Get方法 HttpGet get = new HttpGet("http://localhost:8080/MyTomcat/MyServletTest?username=lisi&password=123456"); //设置服务器接收后数据的读取方式为utf8 get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); try { //执行get方法得到服务器返回的所有数据,在response中 HttpResponse response=client.execute(get); //httpClient访问服务器返回的表头,包含状态码 StatusLine statusLine = response.getStatusLine(); //得到状态码 int num=statusLine.getStatusCode(); if(num==HttpURLConnection.HTTP_OK){ //得到数据的实体 HttpEntity entity= response.getEntity(); //得到输入流 BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String s =br.readLine(); while(s!=null){ System.out.println(s); s=br.readLine(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
POST请求
[code]import java.io.BufferedReader; import java.io.IOException; 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.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 HttpClientDoPostTest { public static void main(String[] args) { // 创建生成client的builder HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client = builder.build();// 生成client HttpPost post = new HttpPost("http://localhost:8080/MyTomcat/MyServletTest"); //如果用户名为中文,则服务器端不需要再转码,因为下边已经封装为UTF-8编码 NameValuePair pair1 = new BasicNameValuePair("username", "zhangsan"); NameValuePair pair2 = new BasicNameValuePair("password", "123456"); 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) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String s = br.readLine(); while (s != null) { System.out.println(s); s = br.readLine(); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果:
相关文章推荐
- HTTPConnection与HTTPClient
- http://blog.sina.com.cn/s/blog_777a9ccb01013maj.html
- Java判断和检查网络
- TCP/IP网络编程 学习笔记_9 --域名系统(DNS)
- TCP/IP网络编程 学习笔记_9 --域名系统(DNS)
- 黑马程序员——java学习14(毕23-24)——网络编程
- http服务器交互get,put,post,delete等概念
- 网络篇----数据安全
- iOS安全系列之一:HTTPS
- Android网络取数据显示到ListView实例
- 卷积神经网络(CNN)笔记
- TCP/IP、Http、Socket的区别
- Http 异步批量下载图片之优化
- IOS--http状态码快速查看
- iOS安全系列之 HTTPS
- android中Http和HttpClient的Get和Post方法的使用
- http异步大量图片下载,并用GridView显示九宫格图片样式
- 通过http user-agent判断是否为手机浏览器
- 运行中修改协调器PAN ID和Channel,协调器广播至所有的设备重启加入新建后的网络
- MFC快速实现网络编程CAsyncSocket类