Java http请求远程连接解决方案

package com.ais.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.faces.context.FacesContext;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class HttpUtils {

    private final static Log log = LogFactory.getLog(HttpUtils.class);

    public static String doHttpPost(String url, String content) {
        
        //System.out.println("---HttpUtils.doHttpPost--url------>"+url);
        //System.out.println("---HttpUtils.doHttpPost--content-->"+content);
        log.info("---HttpUtils.doHttpPost--url------>"+url);
        log.info("---HttpUtils.doHttpPost--content-->"+content);
        
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        OutputStreamWriter out = null;
        HttpURLConnection conn = null;
        try {

            URL console = new URL(url);

            if (url.indexOf("https") != -1) {
                conn = (HttpsURLConnection) console.openConnection();
                //trustAllCerts 
                SslUtils.ignoreSsl();
            } else {
                conn = (HttpURLConnection) console.openConnection();
            }
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type",  "application/json");
            
            
            if(url.indexOf("/login") == -1) {
                //set the sessionID
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
                String sessionId = (String)request.getSession().getAttribute("API_SESSION_ID");
                conn.setRequestProperty("cookie", sessionId);
            }
            
            
            //System.out.println("---HttpUtils.doHttpPost--connect---begin--");
            conn.connect();
            //System.out.println("---HttpUtils.doHttpPost--connect---execute--");

            if (content != null) {
                out = new OutputStreamWriter(conn.getOutputStream());
                out.write(content);
                out.flush();
            }
            
            if(url.indexOf("/login") != -1) {
                //get the sessionID
                String sessionID = null;
                String cookieValue = conn.getHeaderField("set-cookie");
                if(cookieValue != null){
                    sessionID = cookieValue.substring(0, cookieValue.indexOf(";"));
                }else{
                    sessionID = "";
                }
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
                request.getSession().setAttribute("API_SESSION_ID", sessionID);
                
            } 
            
            is = conn.getInputStream();
            //System.out.println("---HttpUtils.doHttpPost--connect---end");
            if (is != null) {
                outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                is.close();

                String sr = new String(outStream.toByteArray());
                //System.out.println("---HttpUtils.doHttpPost--return-->"+sr);
                log.info("---HttpUtils.doHttpPost--return-->"+sr);
                return sr;
            }
            
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        } catch (ProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }

        return null;
    }
    
    public static void main(String[] args) {
        /*
        //String url = "http://localhost:8090/opp/api/oppGetReconFile";
        String url = "http://localhost:8090/opp/api/oppCreateSessionID";
        SessionAPIForm sessionForm = new SessionAPIForm();
        sessionForm.setSourceSysCode("ODS");
        sessionForm.setMerchantRef("00001");
        sessionForm.setEncryptKey("ais123456");
        JSONObject jsonObject = JSONObject.fromObject(sessionForm);
        String result = doHttpPost(url, jsonObject.toString());
        System.out.println(result);
        */
    }
}
 

  • 22
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值