httpClient 请求 xml 格式 json 格式 form 表单格式

 直接贴代码!1!


package com.tianan.payment.biz.utils.bank.unionDirect;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;


/**
 * @author hrtc .
 */
public class HttpUtils {





    /*====================JSON形式请求================*/


    /** xml 报文请求 
   * httpClient请求
   *@param requestXml 请求报文
   *@param requestUrl 请求地址
   *@return
   * @author 
   * @see
   */
  public static String requestHttpXML(String requestXml,String requestUrl){
    HttpClient client = new HttpClient();//创建client对象
    client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);  //设置请求时间 
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");//设置协议和字符编码集
    PostMethod postMethod = new PostMethod(requestUrl);//添加请求路径
    postMethod.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");//设置头部请求方式

    try {
      RequestEntity entity = new StringRequestEntity(requestXml, "text/xml", "UTF-8");//封装参数 
      postMethod.setRequestEntity(entity);//设置参数
      client.executeMethod(postMethod);/发送请求
      if (HttpStatus.SC_OK != postMethod.getStatusCode()){
        throw new BusinessServiceException("http服务接口请求失败!");
      }else{
        return postMethod.getResponseBodyAsString();

      } 
    } catch (HttpException e) {
      throw new BusinessServiceException("http服务请求异常:"+e.getMessage());
    } catch (IOException e) {
      throw new BusinessServiceException("远程服务请求IO异常:"+e.getMessage());
    } catch (Throwable e) {
    	throw new BusinessServiceException("服务器请求异常:"+e.getMessage());
    }
  }







/*====================JSON形式请求================*/


  /**JSON格式请求
   * 
   * @param requestJson
   * @param requestUrl
   * @return
   */

public static String requestHttptoJson(String requestJson,String requestUrl){
	    HttpClient client = new HttpClient();
	    client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);   
	    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	    PostMethod postMethod = new PostMethod(requestUrl);
	    postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
	    try {
	      RequestEntity entity = new StringRequestEntity(requestJson, "application/json", "UTF-8");   
	      postMethod.setRequestEntity(entity);
	      client.executeMethod(postMethod);
	      if (HttpStatus.SC_OK != postMethod.getStatusCode()){	    
	        throw new BusinessServiceException("http服务接口请求失败!");
	      }else{
	        return postMethod.getResponseBodyAsString();
	      } 
	    } catch (HttpException e) {
	      throw new BusinessServiceException("http服务请求异常:"+e.getMessage());
	    } catch (IOException e) {	      
	      throw new BusinessServiceException("远程服务请求IO异常:"+e.getMessage());
	    } catch (Throwable e) {	    	
	    	throw new BusinessServiceException("服务器请求异常:"+e.getMessage());
	    }
	  }



/*====================form形式请求================*/


    /**
     * 超时时间 .
     */
    private static int SOCKET_TIMEOUT = 60000;
    /**
     * 连接超时时间 .
     */
    private static int CONNECT_TIMEOUT = 60000;

    /**
     * 发送http,注意如果调用频繁请自行改造成http连接池.
     * 
     * @param url
     *            请求地址
     * @param dataMap
     *            map请求参数
     * @return 返回字符串
     */
    public static String send(String url, Map<String, String> dataMap) {
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.custom().build();
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setAuthenticationEnabled(false).build();

            HttpPost post = new HttpPost(url);
            post.setProtocolVersion(org.apache.http.HttpVersion.HTTP_1_1);
            post.setConfig(config);

            HttpEntity entity = null;
            List<NameValuePair> formpair = new ArrayList<NameValuePair>();
            
            for (String str : dataMap.keySet().toArray(new String[dataMap.size()])) {
                    //循环添加参数
                    formpair.add(newBasicNameValuePair(str,dataMap.get(str).toString()));
                }
            

            entity = new UrlEncodedFormEntity(formpair, "UTF-8");
            if (entity != null) {
                post.setEntity(entity);
            }
            resp = client.execute(post);
            if (resp.getStatusLine().getStatusCode() == 200) {
                InputStream is = null;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    byte[] buffer = new byte[1024];
                    is = resp.getEntity().getContent();
                    int count = is.read(buffer);
                    while (count != -1) {
                        baos.write(buffer, 0, count);
                        count = is.read(buffer);
                    }
                    return baos.toString("UTF-8");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } finally {
                            
                        }
                    }
                    if (baos != null) {
                        try {
                            baos.close();
                        } finally {
                           
                        }
                    }
                }
            } else {
                throw new RuntimeException(String.format("发送请求失败!",resp.getStatusLine().getStatusCode()));
            }

        } catch (ClientProtocolException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (Exception e) {
                    
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {
                   
                }
            }
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值