手头生正好有一个HTTP Client例子,使用socket 连接。代码如下:

import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class HTTPClient { public static void main(String[] args) { String uri = "/autofei/archive/2010/06/20/5681468.aspx"; int port = 80; String hostname = "blog.csdn.net"; try { InetAddress inetAdd = java.net.InetAddress.getByName(hostname); System.out.println("IP Address is : " + inetAdd.getHostAddress()); if (args.length != 0) { uri = args[0]; port = Integer.parseInt(args[1]); } String host = inetAdd.getHostAddress(); doGet(host, port, uri); } catch (java.net.UnknownHostException e) { e.printStackTrace(); } } public static void doGet(String host, int port, String uri) { Socket socket = null; try { socket = new Socket(host, port); } catch (Exception e) { e.printStackTrace(); } try { StringBuffer sb = new StringBuffer("GET " + uri + " HTTP/1.1/r/n"); sb.append("Accept: */*/r/n"); sb.append("Accept-Language: en/r/n"); sb.append("Accept-Encoding: gzip, deflate/r/n"); sb.append("User-Agent: HTTPClient/r/n"); sb.append("Host: " + host + " " + port + "/r/n"); sb.append("Connection: Keep-Alive/r/n/r/n"); OutputStream socketOut = socket.getOutputStream(); socketOut.write(sb.toString().getBytes()); Thread.sleep(2000); InputStream socketIn = socket.getInputStream(); int size = socketIn.available(); byte[] buffer = new byte[size]; socketIn.read(buffer); System.out.println(new String(buffer)); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } } }

运行上述代码,返回如下:

IP Address is : 211.100.26.77
HTTP/1.1 302 Moved Temporarily
Server: nginx/0.7.65
Date: Fri, 02 Jul 2010 14:27:19 GMT
Content-Type: text/html
Content-Length: 161
Connection: keep-alive
Location: http://www.csdn.net/

<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/0.7.65</center>
</body>
</html>

这个代码基本上是一个最原始的http clinet,模拟了http协议,比如协议头。但是这段代码有几个问题:

首先不能解析动态网页,如aspx等(不知道为什么,请知道的朋友告知,谢谢!)。

其次,服务器返回的是一个二进制byte[],你需要自己解析得到的你需要的内容。

因为我需要拿到的是一个二进制的png图片文件,并不关心头信息,如果能有一个library直接提供解析功能就好了。

Apache common HttpClient 库提供了很好的封装,因此非常简单的几行代码(不及异常处理)就可以了。

public static byte[] getImage(String id) { // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod( "http://hmdb.ca/labm/servlet/labm.mlims.show?ctrl=chemical_structure&hmdb_id=" + id); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); return responseBody; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return null; }

但是这个代码有时会给出如下警告:

Jul 2, 2010 11:42:34 AM org.apache.commons.httpclient.HttpMethodBase getResponseBody
WARNING: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

按照提示应该使用getResponseBodyAsStream。其中最后还有一个将byte[]生成图片并显示,并且判断图片大小后,重新设置图片大小的。下面是我的完整实例:

import java.awt.Image; import java.awt.Toolkit; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HTTPClient { public static byte[] getImage(String id) { // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod( "http://hmdb.ca/labm/servlet/labm.mlims.show?ctrl=chemical_structure&hmdb_id=" + id); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. // NOTE: cause warning for big file // byte[] responseBody = method.getResponseBody(); InputStream in = method.getResponseBodyAsStream(); ByteArrayOutputStream bAOut = new ByteArrayOutputStream(); int c; while ((c = in.read()) != -1) { bAOut.write(c); } return bAOut.toByteArray(); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return null; } public static byte[] getBytesFromInputStream(InputStream is) throws IOException { // Get the size of the file long length = is.available(); System.out.println("length: " + length); if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file "); } // Close the input stream and return bytes is.close(); return bytes; } public static void main(String[] args) { java.awt.Toolkit.getDefaultToolkit(); java.awt.Image image = Toolkit.getDefaultToolkit().createImage( getImage("HMDB00296")); // get image size int height = image.getHeight(null); int width = image.getWidth(null); // resize image size to fit screen if (height > 300) { image = image.getScaledInstance(width * 300 / height, 300, Image.SCALE_SMOOTH); } JFrame frame = new JFrame("Demo"); JPanel main = new JPanel(); JLabel pic = new JLabel("", new ImageIcon(image), JLabel.CENTER); main.add(pic); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(800, 600); frame.getContentPane().add(main); frame.setVisible(true); } }

参考:

http://hc.apache.org/httpclient-3.x/tutorial.html

http://hc.apache.org/httpclient-3.x/apidocs/index.html

转载于:https://www.cnblogs.com/ainima/archive/2010/07/02/6331333.html

HTTP Client 编写相关推荐

  1. websocket server client 编写

    websocket server client 编写 根据RFC文档编写 网络七层简单介绍 websocket 的好处 传输层 websocket应用层协议 根据RFC文档编写 从网络七层开始,写出一 ...

  2. 关于OPC Client 编写

    昨天又有人问我 OPC Client 编写,实际是他们不了解OPC 客户端的工作原理,要想写客户端程序,必须知道OPC对象, OPC逻辑对象模型包括3类对象:OPC server对象.OPC grou ...

  3. 分别在MS-DOS和MySQL Command Line Client编写sql语句

    一.MS-DOS编写sql语句 1.打开cmd,启动mysql  net start mysql(关闭 是net stop mysql) 2.到达mysql的安装目录(比如我的安装目录是F盘),登录m ...

  4. Windbg调优Kafka.Client内存泄露

    从来没写过Blog,想想也是,工作十多年了,搞过N多的架构.技术,不与大家分享实在是可惜了.另外,从传统地ERP行业转到互联网,也遇到了很所前所未有的问题,原来知道有一些坑,但是不知道坑太多太深.借着 ...

  5. 使用Thrift RPC编写程序

    http://dongxicheng.org/search-engine/thrift-rpc/ 1. 概述 本文以C++语言为例介绍了thrift RPC的使用方法,包括对象序列化和反序列化,数据传 ...

  6. ROS基础四之roscpp/rospy节点编写

    roscpp/rospy节点编写 subscriber/advertiser编写 roscpp实例 rospy实例 server/client编写 roscpp实例 rospy实例 actionlib ...

  7. ET框架-13 网络通讯消息的编写

    文章目录 1.首先我们将消息分为两类 1.1 普通消息 1.2 ActLocation的消息 2.编写网络通讯消息 2.1 进入LoginHelper.cs编写代码 2.2 进入Proto文件夹 2. ...

  8. 第五节 RabbitMQ在C#端的应用-消息收发

    原文:第五节 RabbitMQ在C#端的应用-消息收发 版权声明:未经本人同意,不得转载该文章,谢谢 https://blog.csdn.net/phocus1/article/details/873 ...

  9. Spring Cloud 微服务架构

    一.分布式服务框架的发展 1.1 第一代服务框架 代表:Dubbo(Java).Orleans(.Net)等 特点:和语言绑定紧密 1.2 第二代服务框架 代表:Spring Cloud等 现状:适合 ...

最新文章

  1. exchange 2007 碰到NDR
  2. 重磅开源!推荐一个以最优惠的方式购买极客时间课程的开源项目!
  3. 通达信版弘历软件指标_通达信软件指标编写基础教程,10个指标源码祝你股市一帆风顺...
  4. linux提升权限命令提示符,win10如何直接使用命令提示符提高管理员权限?
  5. python cnn程序_python cnn训练(针对Fashion MNIST数据集)
  6. WCF学习之旅----基础篇之EnterpriseServices
  7. window.external的使用
  8. mac文件修改权限设置
  9. AutoCAD2020线型比例修改
  10. VTD(Virtual Test Drive)
  11. 移动端WEB开发过程中小米浏览器的一个坑?
  12. 任意类型变量转换成char类型——sprintf函数使用方法
  13. Aspack壳代码分析
  14. U盘病毒 System Volume Information.exe删不掉
  15. 质量功能展开QFD成功案例解析
  16. Spire.PDF 教程:在C#中显示或隐藏PDF图层
  17. 如何在手机上做读书笔记?手机做读书笔记的软件
  18. 2021年职业病防治法宣传周宣传资料
  19. 华为机试题python版节选(基础编程题)
  20. 吉林大学老师蓝牙点名被赞“有创意”

热门文章

  1. 利用Win32 Debug API打造自己的调试器Debugger
  2. 汇编语言--算术运算指令
  3. oleVariant序列化对象
  4. FastReport报表,FastReport报表加载不出来
  5. Nginx(PHP/fastcgi)的PATH_INFO问题
  6. DB2存储过程语法规则
  7. 红色小方块单击爆炸式展开的菜单代码
  8. EIGRP的路由汇总与认证
  9. ASP.NET MVC 2入门演练 3 - 列表和添加功能
  10. Java 百鸡百钱题