java程序发送HTTP请求

简介:

Java 程序如何发送HTTP请求呢?

有两种实现方式:

1,HttpURLConnection

2,HttpClient

依赖jar包:

 

 

Java代码   收藏代码
  1. Object[] resultArr = HttpSocketUtil.httpRequest(url, ssl22,  
  2.                         forcePost22, json_request, contentType,  
  3.                         session, headerMap, false, null, newEncoding,  
  4.                         15000, 25000);  
  5.                 if(ValueWidget.isNullOrEmpty(resultArr)){  
  6.                     GUIUtil23.errorDialog("404");  
  7.                     return;  
  8.                 }  
  9.                 byte[] resultJsonBytes = (byte[])resultArr[0];  
  10.                 if (ValueWidget.isNullOrEmpty(resultJsonBytes)) {  
  11.                     resultTA.setText("请检查请求的url 是否正确(" + url + ")");  
  12.                     GUIUtil23.warningDialog("返回结果为空.");  
  13.                     return;  
  14.                 }  
  15.                 String resultJson = new String(resultJsonBytes,  
  16.                         SystemHWUtil.CHARSET_GBK);  
  17.                 String resultJson2 = new String(resultJsonBytes,  
  18.                         SystemHWUtil.CHARSET_UTF);  
  19.   
  20.                 // 把http请求结果(json字符串)转化为map  
  21.                 Map<String, Object> resultMap = null;  
  22.                 // if(!"{}".equals(resultJson2.replaceAll(" ", ""))){//"{}"  
  23.                 resultMap = JsonUtils.getMap(resultJson2);// }  
  24.                 // System.out.println(resultMap);  
  25.                 // 判断该接口是否是启动接口,因为启动接口会返回token  
  26.                 if (!ValueWidget.isNullOrEmpty(resultMap)  
  27.                         && resultMap.containsKey(token_label)) {  
  28.                     addInputBox(token_label, (String)resultMap.get(token_label));  
  29.                 }else{//server not offer token  
  30.                       
  31.                 }  
  32.                 // String sessionID = caseDetail.getSessionId();  
  33.                 // if (!ValueWidget.isNullOrEmpty(sessionID)) {  
  34.                 // addInputBox( sessionId_label, sessionID);  
  35.                 // }  
  36.                 if (!ValueWidget.isNullOrEmpty(resultArr[1])) {  
  37.                     session = (String)resultArr[1];  
  38.                 }  
  39.                 if (!ValueWidget.isNullOrEmpty(session)) {  
  40.                     sessionTF.setText(session);  
  41.                 }  

 

httpRequest的返回值是一个数组:

返回数组有4个元素,分别是:

1,request result(byte[]):应答体

2,sessionId

3,contentType:应答的content type;

4,response code:HTTP 状态码

httpRequest 的实现如下:

Java代码   收藏代码
  1. /*** 
  2.      *  
  3.      * @param urlStr 
  4.      * @param ssl 
  5.      * @param forcePost 
  6.      * @param sendData 
  7.      * @param contentType 
  8.      * @param cookie 
  9.      * @param headers 
  10.      * @param isWrite2file 
  11.      * @param destFile 
  12.      * @param charset 
  13.      * @param connectTimeout 
  14.      * @param readTimeout 
  15.      * @return : request result(byte[]) ;sessionId;contentType;response code 
  16.      * @throws Exception 
  17.      */  
  18.     public static Object[] httpRequest(String urlStr, boolean ssl,  
  19.             boolean forcePost, String sendData, String contentType,  
  20.             String cookie, Map<String, String> headers, boolean isWrite2file,  
  21.             Object destFile, String charset, int connectTimeout, int readTimeout)  
  22.             throws Exception {  
  23.         return httpRequest(urlStr, ssl, forcePost, sendData, contentType,  
  24.                 cookie, headers, isWrite2file, destFile, charset,  
  25.                 connectTimeout, readTimeout, null);  
  26.     }  
  27.   
  28. /*** 
  29.      *  
  30.      * @param urlStr 
  31.      * @param sendData 
  32.      * @param contentType 
  33.      *            : default is application/x-www-form-urlencoded 
  34.      * @param cookie 
  35.      * @param headers 
  36.      *            : request header 
  37.      * @param isWrite2file 
  38.      *            : whether write to file 
  39.      * @param destFile 
  40.      *            file which will be written 
  41.      * @return : request result(byte[]) ;sessionId;contentType;response code 
  42.      * @throws Exception 
  43.      */  
  44.     public static Object[] httpRequest(String urlStr, boolean ssl,  
  45.             boolean forcePost, String sendData, String contentType,  
  46.             String cookie, Map<String, String> headers, boolean isWrite2file,  
  47.             Object destFile, String charset, int connectTimeout,  
  48.             int readTimeout, String sizeHeadKey) throws Exception {  
  49.         // URL url = new URL(urlString);  
  50.         if (isDetail)  
  51.             System.out.println("ssl:" + ssl);  
  52.         HttpURLConnection huc = beforeConnect(urlStr, ssl, forcePost, sendData,  
  53.                 contentType, cookie, headers, charset, connectTimeout,  
  54.                 readTimeout);  
  55.   
  56.         File writeFile = null;  
  57.         if (destFile instanceof File) {  
  58.             writeFile = (File) destFile;  
  59.         } else {  
  60.             if (!ValueWidget.isNullOrEmpty(destFile)) {  
  61.                 writeFile = new File((String) destFile);  
  62.             }  
  63.         }  
  64.         if (isDetail)  
  65.             System.out.println("writeFile:" + writeFile);  
  66.         //应答码,返回码  
  67.         int resCode = huc.getResponseCode();  
  68.         byte[] result = connection(resCode,huc, isWrite2file, writeFile, sizeHeadKey);  
  69.         if (!isWrite2file && (result == null)) {  
  70.             System.out  
  71.                     .println("[HttpSocketUtil.httpRequest]connection return is null.");  
  72.             return null;  
  73.         }  
  74.         if (!ValueWidget.isNullOrEmpty(result)) {  
  75.             System.out.println("read result length of bytes:" + result.length);  
  76.         }  
  77.         Object[] retArr = new Object[3];  
  78.         String session_value = huc  
  79.                 .getHeaderField(SystemHWUtil.KEY_HEADER_COOLIE);  
  80.         // Map<String, List<String>> responseHeaders = huc.getHeaderFields();  
  81.         // for (Iterator<?> it = responseHeaders.keySet().iterator();  
  82.         // it.hasNext();) {  
  83.         // System.out.println("key:" + it.next());  
  84.         // }  
  85.         if (ValueWidget.isHasValue(session_value)) {  
  86.             String[] sessionId = session_value.split(";");  
  87.             retArr[1] = sessionId[0];  
  88.             if (isDetail) {  
  89.                 System.out  
  90.                         .println("[HttpSocketUtil.httpRequest]session id is :"  
  91.                                 + sessionId[0]);  
  92.             }  
  93.         }  
  94.         retArr[2] = huc.getContentType();  
  95.         retArr[3] = resCode;  
  96.         retArr[0] = result;  
  97.         // if (isWrite2file && destFile != null) {  
  98.         // byte[] bytes = (byte[]) result;  
  99.         //  
  100.         // FileUtils.writeBytesToFile(bytes, writeFile);  
  101.         // }  
  102.         return retArr;  
  103.     }  

源码见:com.http.util.HttpSocketUtil 

下载地址:http://pan.baidu.com/s/1hqeXBhE 

相关文章
|
设计模式 Java Spring
Java 设计模式之责任链模式:优雅处理请求的艺术
责任链模式通过构建处理者链,使请求沿链传递直至被处理,实现发送者与接收者的解耦。适用于审批流程、日志处理等多级处理场景,提升系统灵活性与可扩展性。
1456 2
|
人工智能 监控 安全
智慧工地解决方案,java智慧工地程序代码
智慧工地系统融合物联网、AI、大数据等技术,实现对施工现场“人、机、料、法、环”的全面智能监控与管理,提升安全、效率与决策水平。
447 2
|
安全 Java
Java异常处理:程序世界的“交通规则
Java异常处理:程序世界的“交通规则
481 98
|
存储 Java 编译器
对比Java学习Go——程序结构与变量
本节对比了Java与Go语言的基础结构,包括“Hello, World!”程序、代码组织方式、入口函数定义、基本数据类型及变量声明方式。Java强调严格的面向对象结构,所有代码需置于类中,入口方法需严格符合`public static void main(String[] args)`格式;而Go语言结构更简洁,使用包和函数组织代码,入口函数为`func main()`。两种语言在变量声明、常量定义、类型系统等方面也存在显著差异,体现了各自的设计哲学。
494 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
949 0
|
运维 Cloud Native Java
postman发起post请求遇到报错:java.io.FileNotFoundException (文件名、目录名或卷标语法不正确。)
遇到bug报错,多猜可能的原因,控制变量反复测试,直至找到问题的关键,然后再思考如何解决或者回避。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来
|
存储 Java 数据库连接
【YashanDB知识库】Java程序调用存储过程,在提取clob时报YAS-00004
【YashanDB知识库】Java程序调用存储过程,在提取clob时报YAS-00004
|
Java Apache
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
hbase从集群中有8台regionserver服务器,已稳定运行了5个多月,8月15号,发现集群中4个datanode进程死了,经查原因是内存 outofMemory了(因为这几台机器上部署了spark,给spark开的...
1085 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
zookeeper watch的定义如下:watch事件是一次性触发器,当watch监视的数据发生变化时,通知设置了该watch的client,即watcher。
1271 0

热门文章

最新文章