curl java 模拟http请求

项目需求java模拟http请求,获取dns解析 tcp连接等详细耗时信息。

java api中提供的urlConnection 及apache提供的httpClient都不能胜任该需求,二次开发太费时间。于是google之。

最后 得出两种解决办法:

一是使用HTTP4J。

该开源项目使用socket方式,模拟请求,记录时间戳,基本满足需求。对于header自定义等细节,可在此基础上比较方便的二次开发。只是,其中有一些bug需要修复,如https链接时获取不到ssl时间等。使用该项目的风险在于不稳定和不可控性。


稍作改动后的http4j代码。

http://download.csdn.net/detail/zhongyuan_1990/8837281


二是使用curl。

google之,curl本身没有对java的支持,由第三份提供了binding用来使用curl。可能是笔者能力有限,未能成功在windows编译它。google也没有找到相关javacurl.dll的资源下载。最后不得不放弃。选择使用命令行的模式操作curl。

java 使用curl命令 demo

[java] view plain copy
  1. package com.netbirdtech.libcurl.test;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6.   
  7. public class test {  
  8.     public static void main(String[] args) {  
  9.         String []cmds = {"curl""-i""-w""状态%{http_code};DNS时间%{time_namelookup};"  
  10.                 + "等待时间%{time_pretransfer}TCP 连接%{time_connect};发出请求%{time_starttransfer};"  
  11.                 + "总时间%{time_total}","http://www.baidu.com"};  
  12.         ProcessBuilder pb=new ProcessBuilder(cmds);  
  13.         pb.redirectErrorStream(true);  
  14.         Process p;  
  15.         try {  
  16.             p = pb.start();  
  17.             BufferedReader br=null;  
  18.             String line=null;  
  19.               
  20.             br=new BufferedReader(new InputStreamReader(p.getInputStream()));  
  21.             while((line=br.readLine())!=null){  
  22.                     System.out.println(" "+line);  
  23.             }  
  24.             br.close();  
  25.         } catch (IOException e) {  
  26.             // TODO Auto-generated catch block  
  27.             e.printStackTrace();  
  28.         }  
  29.           
  30.     }  
  31. }  
原文地址:https://www.cnblogs.com/hzcya1995/p/13317585.html