欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

post get HttpClient

程序员文章站 2022-04-24 20:07:20
...
package com.common;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.Base64Utils;

/**
*
* @author Administrator
*
*/
public class HttpClient {
public static Logger logger = LogManager.getLogger("xmllog");
public static String HMAC_SHA1_ALGORITHM = "HmacSHA1";

/**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                      // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(param);
            writer.flush();

//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
     // 打印返回报文
     StringBuffer loggerBugffer = new StringBuffer();//清空日志缓存
     loggerBugffer.append("*************客户登录返回报文************ /n");
     loggerBugffer.append(result+"/n");
     loggerBugffer.append("*************客户登录返回报文************ ");
     logger.info(loggerBugffer);
     // 打印返回报文
        return result;
    }
   
    /**
     *
     * DESCRIPTION:发送http请求
     * @author
     * @date 2016年6月2日
     * sendPost 方法
     * @param url
     * @param param
     * @param charset
     * @return
     * @return String
     * @throws
     */
    public static String sendPost(String url, String param,String charset) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/xml;charset="+charset); // 设置发送数据的格式 
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            writer.write(param);
            writer.flush();

//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
   
    /**
     *
     * DESCRIPTION:发送post参数请求
     * @author
     * @date 2016年6月2日
     * sendPost 方法
     * @param url
     * @param param
     * @return
     * @return String
     * @throws
     */
    public static String sendPostparam(String url, String param,String charset) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="+charset); // 设置发送数据的格式 
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            writer.write(param);
            writer.flush();

//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
   
   
    /**
     *
     * DESCRIPTION:发送JSON
     * @author
     * @date 2016年6月2日
     * sendPost 方法
     * @param url
     * @param param
     * @return
     * @return String
     * @throws
     */
    public static String sendJson(String url, String param) {
    try {

             URL add_url = new URL(url);

             HttpURLConnection connection = (HttpURLConnection)add_url.openConnection();

             connection.setDoInput(true);

             connection.setDoOutput(true);

             connection.setRequestMethod("POST");

             connection.setUseCaches(false);

             connection.setInstanceFollowRedirects(true);
             connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 
             connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式 
            


             connection.connect();

             DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            
             out.write(param.getBytes("utf-8"));
            

             out.flush();

             out.close();

             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

             String lines;

             StringBuffer sbf = new StringBuffer();

              while ((lines = reader.readLine()) != null) {

                     lines = new String(lines.getBytes(), "utf-8");

                     sbf.append(lines);

                 }

                 System.out.println(sbf);

                 reader.close();

                 // 断开连接

                 connection.disconnect();
                 return sbf.toString();

         } catch (MalformedURLException e) {

             // TODO Auto-generated catch block

             e.printStackTrace();

         } catch (IOException e) {

             // TODO Auto-generated catch block

             e.printStackTrace();

         }
    return null;
    }
   
    public static String sendPostDoCA(String url, String param,String charset,String signature) {
        BufferedReader in = null;
        DataOutputStream out=null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/xml;charset="+charset); // 设置发送数据的格式 
            conn.setRequestProperty("Content-Signature", "HMAC-SHA1 " + signature); // 设置发送数据的格式 

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new DataOutputStream(conn.getOutputStream());
           
            out.write(param.getBytes("utf-8"));
            out.flush();

            out.close();
//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     *
     * DESCRIPTION:发送JSON
     * @author
     * @date 2016年6月2日
     * sendGet 方法
     * @param url
     * @param param
     * @return
     * @return String
     * @throws
     */
   
    public static String sendGet(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        if(!"".equals(param) && param!=null){
       int index = url.indexOf("?");
       if(index > 0){
       url =  url+"&"+param;
       }else{
       url =  url+"?"+param;
       }
       }
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.connect();
                      // 发送POST请求必须设置如下两行
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
          
//            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//            writer.write(param);
//            writer.flush();

//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(param);
//            // flush输出流的缓冲
//            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
           
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
           logger.error("HttpClient.sendGet 发送 GET 请求出现异常:"+e.getMessage(),e);
            System.out.println("发送 GET 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
     // 打印返回报文
     StringBuffer loggerBugffer = new StringBuffer();//清空日志缓存
     loggerBugffer.append("*************客户登录返回报文************ /n");
     loggerBugffer.append(result+"/n");
     loggerBugffer.append("*************客户登录返回报文************ ");
     logger.info(loggerBugffer);
     // 打印返回报文
        return result;
    }
}