HttpRequest工具来

HttpRequestUtil 工具类

package com.ningpai.m.util;

import com.ningpai.util.MyLogger;
import net.sf.json.JSONObject;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.*;


/**
 * Created by xcy on 2018/10/19.
 */
public class HttpRequestUtil {


    /** 记录日志对象 */
    private static final MyLogger LOGGER = new MyLogger(HttpRequestUtil.class);

        /**
         * 发送get请求
         * @param url
         * @param decodeCharset
         * @return
         */
        public static String sendGetRequest(String url, String decodeCharset) {
            HttpClient httpclient = new DefaultHttpClient();
            String responseContent = null;
            HttpGet httpGet = new HttpGet(url);
            HttpEntity entity = null;
            try {
                HttpResponse response = httpclient.execute(httpGet);
                System.out.println(response);
                entity = response.getEntity();
                if (null != entity) {
                    responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
                }
            } catch (Exception e) {
                LOGGER.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下", e);
            } finally {
                try {
                    EntityUtils.consume(entity);
                    httpclient.getConnectionManager().shutdown();
                } catch (Exception ex) {
                    LOGGER.error("net io excepiton", ex);
                }
            }
            return responseContent;
        }

    /**
     * post 请求
     * @param reqURL
     * @param  data  可以为param="key1=value1&key2=value2"的一串字符串,或者是jsonObject
     * @return
     */
        public static String sendHttpPostRequest(String reqURL, String data) {
            HttpClient httpclient = new DefaultHttpClient();
            String respStr = "";
            try {
                HttpPost httppost = new HttpPost(reqURL);
                StringEntity strEntity = new StringEntity(data, "UTF-8");
                strEntity.setContentType("application/x-www-form-urlencoded");
                httppost.setEntity(strEntity);
                LOGGER.info(EntityUtils.toString(strEntity));
                LOGGER.info("executing request " + httppost.getRequestLine());

                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();

                if (resEntity != null) {
                    LOGGER.info("返回数据长度: " + resEntity.getContentLength());
                    respStr = EntityUtils.toString(resEntity);
                    LOGGER.info("respStr " + respStr);
                }

            } catch (ClientProtocolException e) {
                LOGGER.error("sendHttpPostRequest : " ,e);
            } catch (IOException e) {
                LOGGER.error("sendHttpPostRequest : " ,e);
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            return respStr;
        }

        /**
         * 发送post请求
         * @param url
         * @param params
         * @return
         * @throws Exception
         */
        public static String sendHttpPostRequest(String url, Map<String, String> params) {
            String respStr = "";
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
            httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            LOGGER.info("url: " + url);
            LOGGER.info("params: " + params);
            try {
                HttpPost post = new HttpPost(url);
                List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
                post.setEntity(entity);
                HttpResponse response = httpclient.execute(post);
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    LOGGER.info("返回数据长度: " + resEntity.getContentLength());
                    respStr = EntityUtils.toString(resEntity);
                    LOGGER.info("respStr " + respStr);
                }
            } catch (ClientProtocolException e) {
                LOGGER.error("sendHttpPostRequest : " +e);
            } catch (IOException e) {
                LOGGER.error("sendHttpPostRequest : " +e);
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            return respStr;
        }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
            String params = "bankcard=6217856101018144878&key=316fcfd892e7e4d24ded8699f1f7d957";
            String resultstr = HttpRequestUtil.sendHttpPostRequest("http://apis.juhe.cn/bankcardcore/query", params);
            System.out.println(resultstr);
            ObjectMapper mapper = new ObjectMapper();
               try {
                   Map map = mapper.readValue(resultstr, Map.class);
                   Set<Map.Entry> set = map.entrySet();
                   for (Map.Entry entry : set) {
                       System.out.println(entry.getKey() + "==" + entry.getValue());
                   }
               }catch(IOException ioe){
                     ioe.printStackTrace();
               }
        }

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值