描述: http通讯基础类
package com.founder.ec.web.util.payments.payeco.http;
import com.founder.ec.web.util.payments.payeco.http.ssl.SslConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.SortedMap;
/**
* 描述: http通讯基础类
*
*/
public class HttpClient {
private int status;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static String REQUEST_METHOD_GET = "GET";
public static String REQUEST_METHOD_POST = "POST";
public String send(String postURL, String requestBody,
String sendCharset, String readCharset) {
return send(postURL,requestBody,sendCharset,readCharset,300,300);
}
public String send(String postURL, String requestBody,
String sendCharset, String readCharset,String RequestMethod) {
return send(postURL,requestBody,sendCharset,readCharset,300,300,RequestMethod);
}
/**
* @param postURL 访问地址
* @param requestBody paramName1=paramValue1¶mName2=paramValue2
* @param sendCharset 发送字符编码
* @param readCharset 返回字符编码
* @param connectTimeout 连接主机的超时时间 单位:秒
* @param readTimeout 从主机读取数据的超时时间 单位:秒
* @return 通讯返回
*/
public String send(String url, String requestBody,
String sendCharset, String readCharset,int connectTimeout,int readTimeout) {
try {
return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,REQUEST_METHOD_POST);
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("发送请求[" + url + "]失败," + ex.getMessage());
return null;
}
}
/**
* @param postURL 访问地址
* @param requestBody paramName1=paramValue1¶mName2=paramValue2
* @param sendCharset 发送字符编码
* @param readCharset 返回字符编码
* @param connectTimeout 连接主机的超时时间 单位:秒
* @param readTimeout 从主机读取数据的超时时间 单位:秒
* @param RequestMethod GET或POST
* @return 通讯返回
*/
public String send(String url, String requestBody,
String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod) {
try {
return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,RequestMethod);
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("发送请求[" + url + "]失败," + ex.getMessage());
return null;
}
}
public String connection(String postURL, String requestBody,
String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod)throws Exception {
if(REQUEST_METHOD_POST.equals(RequestMethod)){
return postConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);
}else if(REQUEST_METHOD_GET.equals(RequestMethod)){
return getConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);
}else{
return "";
}
}
@SuppressWarnings("rawtypes")
public String getConnection(String url, String requestBody,
String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {
// Post请求的url,与get不同的是不需要带参数
HttpURLConnection httpConn = null;
try {
if (!url.contains("https:")) {
URL postUrl = new URL(url);
// 打开连接
httpConn = (HttpURLConnection) postUrl.openConnection();
} else {
SslConnection urlConnect = new SslConnection();
httpConn = (HttpURLConnection) urlConnect.openConnection(url);
}
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=" + sendCharset);
if(reqHead!=null&&reqHead.size()>0){
Iterator iterator =reqHead.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = (String)reqHead.get(key);
httpConn.setRequestProperty(key,val);
}
}
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
// 连接主机的超时时间(单位:毫秒)
httpConn.setConnectTimeout(1000 * connectTimeout);
// 从主机读取数据的超时时间(单位:毫秒)
httpConn.setReadTimeout(1000 * readTimeout);
// 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行 connect。
httpConn.connect();
int status = httpConn.getResponseCode();
setStatus(status);
if (status != HttpURLConnection.HTTP_OK) {
System.out.print("发送请求失败,状态码:[" + status + "] 返回信息:"
+ httpConn.getResponseMessage());
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), readCharset));
StringBuffer responseSb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseSb.append(line.trim());
}
reader.close();
return responseSb.toString().trim();
} finally {
httpConn.disconnect();
}
}
@SuppressWarnings("rawtypes")
public String postConnection(String postURL, String requestBody,
String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {
// Post请求的url,与get不同的是不需要带参数
HttpURLConnection httpConn = null;
try {
if (!postURL.contains("https:")) {
URL postUrl = new URL(postURL);
// 打开连接
httpConn = (HttpURLConnection) postUrl.openConnection();
} else {
SslConnection urlConnect = new SslConnection();
httpConn = (HttpURLConnection) urlConnect.openConnection(postURL);
}
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
httpConn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpConn.setDoInput(true);
// 设定请求的方法为"POST",默认是GET
httpConn.setRequestMethod("POST");
// Post 请求不能使用缓存
httpConn.setUseCaches(false);
//进行跳转
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=" + sendCharset);
if(reqHead!=null&&reqHead.size()>0){
Iterator iterator =reqHead.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String val = (String)reqHead.get(key);
httpConn.setRequestProperty(key,val);
}
}
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
// 连接主机的超时时间(单位:毫秒)
httpConn.setConnectTimeout(1000 * connectTimeout);
// 从主机读取数据的超时时间(单位:毫秒)
httpConn.setReadTimeout(1000 * readTimeout);
// 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行 connect。
httpConn.connect();
DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
out.write(requestBody.getBytes(sendCharset));
out.flush();
out.close();
int status = httpConn.getResponseCode();
setStatus(status);
if (status != HttpURLConnection.HTTP_OK) {
System.out.print("发送请求失败,状态码:[" + status + "] 返回信息:"
+ httpConn.getResponseMessage());
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), readCharset));
StringBuffer responseSb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseSb.append(line.trim());
}
reader.close();
return responseSb.toString().trim();
} finally {
httpConn.disconnect();
}
}
public static void main(String[] args) {
}
}
描述: http通讯基础类的更多相关文章
- 基于 Paramiko 的 SSH 通讯类
# -*- coding: UTF-8 -*-import paramikoimport time################################################### ...
- 多平台Client TCP通讯组件
Beetle.NetPackage是一个多平台Client Socket TCP通讯组件(Apache License 2.0),组件制统一的对象协议制定规则,可以灵活方便地通过对象来描述TCP通讯交 ...
- C# 串口操作系列(5)--通讯库雏形
C# 串口操作系列(5)--通讯库雏形 标签: 通讯c#数据分析byteclassstring 2010-08-09 00:07 21378人阅读 评论(73) 收藏 举报 分类: 通讯类库设计(4 ...
- 发送http请求
public static String httpGetSend(String url) { String responseMsg = ""; HttpClient httpCli ...
- java socket编程(也是学习多线程的例子)详细版----转
7.2 面向套接字编程 我们已经通过了解Socket的接口,知其所以然,下面我们就将通过具体的案例,来熟悉Socket的具体工作方式 7.2.1使用套接字实现基于TCP协议的服务器和客户机程序 ...
- [置顶] Django 微信开发(一)——环境搭建
Django 微信开发(一)——环境搭建 随着移动互联网时代的到来,微信——一个改变着我们生活的产品悄悄走近了我们的生活.我们不得不觉得自己很幸运,自己能在这个世界上遇到像QQ.微博.微信这样优秀的产 ...
- 参考sectools,每个人至少查找5种安全工具、库等信息并深入研究至少两种并写出使用教程
1.Nessus Nessus是免费网络漏洞扫描器,它可以运行于几乎所有的UNIX平台之上.它不仅能永久升级,还免费提供多达11000种插件(但需要注册并接受EULA-acceptance--终端用户 ...
- 利用Java反射机制优化简单工厂设计模式
之前项目有个需求,审批流程的时候要根据配置发送信息:发送短信.发送邮件.当时看到这个就想到要用工厂模式,为什么要用工厂模式呢?用工厂模式进行大型项目的开发,可以很好的进行项目并行开发.就是一个程序员和 ...
- 工控随笔_22_关于Profibus网络接线的规则
最近在做一个项目调试,用的是西门子的PLC,416-2 DP,下面挂了几个DP子网,在进行现场网络测试的时候,有几个走的DP网络的 绝对值编码器,无论怎么弄DP网络不能联通. 一开始我以为DP网线接的 ...
随机推荐
- jdk9+版本的bug
今天从jvm大神"你假笨"的公众号上,看到一个jdk 9+版本的编译bug,记录一下: public class JavacEvalBug{ private static Stri ...
- Using a Virtex Device to Drive 5V CMOS-Level Signals
Must tri-state outputs and use an external resistor to pull up to 5V To drive 5V CMOS-level inputs, ...
- 通过JPA注解映射视图的实体类 jpa 视图 无主键 @Query注解的用法(Spring Data JPA) jpa 使用sql语句
参考: https://blog.csdn.net/qq465235530/article/details/68064074 https://www.cnblogs.com/zj0208/p/6008 ...
- mock获取入参数并动态设置返回值
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of ...
- .NET “底层”异步编程模式——异步编程模型(Asynchronous Programming Model,APM)
本文内容 异步编程类型 异步编程模型(APM) 参考资料 首先澄清,异步编程模式(Asynchronous Programming Patterns)与异步编程模型(Asynchronous Prog ...
- 谷歌Chrome浏览器无法安装插件的解决方法
Chrome浏览器已替代了个人多年使用的遨游浏览器,但众所周知,国内的环境无法正常登录谷歌账户.无法访问应用商店,而Chrome主版本号大于66的只能从Chrome应用商店下载并安装插件,这不是死结吗 ...
- netstat使用--10个常用的命令
1.列出所有的端口 netstat -a 列出TCP协议的端口 netstat -at UDP协议的端口 netstat -au 2.列出处于监听状态的socket netstat - ...
- Attempt to present <TestViewController2: 0x7fd7f8d10f30> on <ViewController: 0x7fd7f8c054c0> whose view is not in the window hierarchy!
当 storyboard里面的 按钮 即连接了 类文件里面的点击方法 又 连接了 storyboard里 另一个 控制器的 modal 就会出现类似Attempt to present & ...
- [svc]HTTPS证书生成原理和部署细节
参考: http://www.barretlee.com/blog/2015/10/05/how-to-build-a-https-server/ 今天摸索了下 HTTPS 的证书生成,以及它在 Ng ...
- mysql 存储引擎对索引的支持
一.首先给出mysql官方文档给出的不同存储引擎对索引的支持 从上面的图中可以得知,mysql 是支持hash索引的,但支持和不支持又和具体的存储引擎有关系.从图中看到InnoDB是支持Btree索引 ...