java实现http请求

package com.nfs.http;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.httpclient.HttpException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunline.ark.support.exception.ProcessException;

/**
 * 对外接口调用
 */
public class HttpsClient {  
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    /**
     * 发送https请求
     * @param url  请求地址
     * @param xml  xml
     * @param charSet 编码格式
     * @return
     */
    @SuppressWarnings({ "resource", "deprecation" })
    public String sendHttpsPost(String url,String xml, String charSet){  
        logger.debug("请求地址:{}", url);
        HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
            httpClient = new DefaultHttpClient();  
            httpPost = new HttpPost(url);  
            httpPost.setEntity(new InputStreamEntity(new ByteArrayInputStream(xml.getBytes()), ContentType.create(
                    "application/xml", charSet)));
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,charSet);
                }  
            } 
            logger.debug("接收到的HTTPS响应原始报文:[{}]", result);
        } catch (UnsupportedEncodingException e) {
            logger.error("交易报文编码异常[{}]",e);
            throw new ProcessException("不支持编码异常",e);
        } catch (HttpException e) {
            logger.error("交易https连接异常[{}]",e);
            throw new ProcessException("交易链路异常",e);
        } catch (IOException e) {
            logger.error("交易https读取异常[{}]",e);
            throw new ProcessException("交易http读取异常",e);
        } catch (Exception e){
            logger.error("交易报文编码异常[{}]",e);
            throw new ProcessException("不支持编码异常",e); 
        }  
        return result;  
    }
    /**
     * 发送 HTTP请求
     * @param url   请求地址
     * @param json  json报文
     * @param requestName 请求参数名
     * @param charset 编码格式
     * @return
     */
    @SuppressWarnings({ "resource", "deprecation" })
     public  String sendHttpPost(String url, String json, String requestName,String charset){  
         logger.debug("请求地址:{}", url);
         HttpClient httpclient = new DefaultHttpClient();
        StringBuilder sb = new StringBuilder();
        try {
            HttpPost post = new HttpPost(url);
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            list.add(new BasicNameValuePair(requestName, json));
            post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
            StringEntity entity = new StringEntity(json, "utf-8");
              entity.setContentEncoding("utf-8");
              entity.setContentType("application/json;charset=UTF-8");
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            InputStream is = null;
            try {
                is = response.getEntity().getContent();
                BufferedInputStream bis = new BufferedInputStream(is);
                InputStreamReader reader = new InputStreamReader(bis, charset);
                int len = 0;
                char[] chars = new char[1024];
                while ((len = reader.read(chars)) != -1) {                    
                    sb.append(Arrays.copyOf(chars, len));
                }
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                }
                try {
                    is.close();
                } catch (IOException e) {
                }
                    
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();  
     }  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值