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&paramName2=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&paramName2=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通讯基础类的更多相关文章

  1. 基于 Paramiko 的 SSH 通讯类

    # -*- coding: UTF-8 -*-import paramikoimport time################################################### ...

  2. 多平台Client TCP通讯组件

    Beetle.NetPackage是一个多平台Client Socket TCP通讯组件(Apache License 2.0),组件制统一的对象协议制定规则,可以灵活方便地通过对象来描述TCP通讯交 ...

  3. C# 串口操作系列(5)--通讯库雏形

    C# 串口操作系列(5)--通讯库雏形 标签: 通讯c#数据分析byteclassstring 2010-08-09 00:07 21378人阅读 评论(73) 收藏 举报  分类: 通讯类库设计(4 ...

  4. 发送http请求

    public static String httpGetSend(String url) { String responseMsg = ""; HttpClient httpCli ...

  5. java socket编程(也是学习多线程的例子)详细版----转

    7.2 面向套接字编程    我们已经通过了解Socket的接口,知其所以然,下面我们就将通过具体的案例,来熟悉Socket的具体工作方式 7.2.1使用套接字实现基于TCP协议的服务器和客户机程序  ...

  6. [置顶] Django 微信开发(一)——环境搭建

    Django 微信开发(一)——环境搭建 随着移动互联网时代的到来,微信——一个改变着我们生活的产品悄悄走近了我们的生活.我们不得不觉得自己很幸运,自己能在这个世界上遇到像QQ.微博.微信这样优秀的产 ...

  7. 参考sectools,每个人至少查找5种安全工具、库等信息并深入研究至少两种并写出使用教程

    1.Nessus Nessus是免费网络漏洞扫描器,它可以运行于几乎所有的UNIX平台之上.它不仅能永久升级,还免费提供多达11000种插件(但需要注册并接受EULA-acceptance--终端用户 ...

  8. 利用Java反射机制优化简单工厂设计模式

    之前项目有个需求,审批流程的时候要根据配置发送信息:发送短信.发送邮件.当时看到这个就想到要用工厂模式,为什么要用工厂模式呢?用工厂模式进行大型项目的开发,可以很好的进行项目并行开发.就是一个程序员和 ...

  9. 工控随笔_22_关于Profibus网络接线的规则

    最近在做一个项目调试,用的是西门子的PLC,416-2 DP,下面挂了几个DP子网,在进行现场网络测试的时候,有几个走的DP网络的 绝对值编码器,无论怎么弄DP网络不能联通. 一开始我以为DP网线接的 ...

随机推荐

  1. IBM Thread and Monitor Dump Analyzer for Java解决生产环境中的性能问题

    这个工具的使用和 HeapAnalyzer 一样,非常容易,同样提供了详细的 readme 文档,这里也简单举例如下: #/usr/java50/bin/java -Xmx1000m -jar jca ...

  2. FT232H FT2232H FT4232H

    The FT232H is the single channel version, the FT2232H is the dual-channel, and there is also anFT423 ...

  3. sql server management studio 查询的临时文件路径

    C:\Users\你的登录名称\Documents\SQL Server Management Studio\Backup Files C:\Users\你的登录名称\AppData\Local\Te ...

  4. WIN10平板 如何修改网络IP地址为固定

    右击网络,属性,更改适配器设置,然后可以找到当前的无线网络   然后依次点开即可修改IP地址

  5. grid - 初识

    Grid有三个参数 目前介绍以下两种:grid.inline-grid <view class="grid"> <view class='grid-row'> ...

  6. Spark机器学习(5):SVM算法

    1. SVM基本知识 SVM(Support Vector Machine)是一个类分类器,能够将不同类的样本在样本空间中进行分隔,分隔使用的面叫做分隔超平面. 比如对于二维样本,分布在二维平面上,此 ...

  7. Javascript框架的自定义事件(转)

    很多 javascript 框架都提供了自定义事件(custom events),例如 jquery.yui 以及 dojo 都支持“document ready”事件.而部分自定义事件是源自回调(c ...

  8. sql in not in 案例用 exists not exists 代替

    from AppStoke B WHERE B.Opencode=A.Code) in用extist代替 select distinct * from Stoke where Code not in ...

  9. 每日英语:Upgrade Your Life: How to speed up your PC (or Mac)

    Is your desktop or laptop computer starting to feel a little poky? Even after just a few months of u ...

  10. PHP可变参数

    0x00 缘起 在laravel的源码里经常可以看到下面的函数形式 $func(...$args) 0x01 可变参数旧写法 这表示$func支持可变参数,在php5.6之前则是在函数体内调用 fun ...