http请求

 http工具类:

/**
 * Author: hezishan
 * Date: 2018/5/11.
 * Description: http工具类
 **/
public class HttpUtil {

    protected static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String getUrl(String url, String encoding)
            throws ClientProtocolException, IOException {
        return getUrl(url, encoding, null);
    }

    public static String getUrl(String url, String encoding, Integer readLine)
            throws ClientProtocolException, IOException {
        StringBuffer resultStr = new StringBuffer();
        String result = new String();
        // 默认的client类。
        HttpClient httpClient = new DefaultHttpClient();
        try {
            // 设置为get取连接的方式.
            HttpGet get = new HttpGet(url);
            // 得到返回的response.
            HttpResponse httpResponse = httpClient.execute(get);
            // 得到返回的client里面的实体对象信息.
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    logger.debug("内容编码是:" + entity.getContentEncoding());
                    logger.debug("内容类型是:" + entity.getContentType());
                    // 得到返回的主体内容.
                    InputStream inStream = entity.getContent();
                    if (readLine == null) {
                        byte[] data = StreamTool.readInputStream(inStream);
                        result = new String(data, encoding);
                    } else {
                        int i = 0;
                        try {
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(inStream, encoding));
                            String msg = null;
                            while ((msg = reader.readLine()) != null
                                    || i < readLine) {
                                resultStr.append(msg);
                                i++;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            inStream.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();// 最后关掉链接。
                httpClient = null;
            }
        }
        if (readLine == null) {
            return result;
        } else {
            return resultStr.toString();
        }
    }

    public static String getSSLUrl(String url, String encoding)
            throws Exception {
        StringBuffer resultStr = new StringBuffer();
        // 默认的client类。
        HttpClient httpClient = new SSLClient();
        try {
            // 设置为get取连接的方式.
            HttpGet get = new HttpGet(url);
            // 得到返回的response.
            HttpResponse httpResponse = httpClient.execute(get);
            // 得到返回的client里面的实体对象信息.
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    logger.debug("内容编码是:" + entity.getContentEncoding());
                    logger.debug("内容类型是:" + entity.getContentType());
                    // 得到返回的主体内容.
                    InputStream instream = entity.getContent();
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(instream, encoding));
                        String msg = null;
                        while ((msg = reader.readLine()) != null) {
                            resultStr.append(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        instream.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();// 最后关掉链接。
                httpClient = null;
            }
        }
        return resultStr.toString();
    }

    public static String postUrlWithParams(String url, Map params,
                                           String encoding) throws Exception {
        String resultStr = null;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpPost httpost = new HttpPost(url);
            // 添加参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null && params.keySet().size() > 0) {
                Iterator iterator = params.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Entry) iterator.next();
                    nvps.add(new BasicNameValuePair((String) entry.getKey(),
                            (String) entry.getValue()));
                }
            }
            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
            HttpResponse httpResponse = httpclient.execute(httpost);
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
                HttpEntity entity = httpResponse.getEntity();
                resultStr = dump(entity, encoding);
                logger.debug("Post logon cookies:");
                List<Cookie> cookies = httpclient.getCookieStore().getCookies();
                if (cookies.isEmpty()) {
                    logger.debug("None");
                } else {
                    for (int i = 0; i < cookies.size(); i++) {
                        System.out.println("- " + cookies.get(i).toString());
                    }
                }
            }
        } finally {
            // 关闭请求
            httpclient.getConnectionManager().shutdown();
        }
        return resultStr;
    }

    private static String dump(HttpEntity entity, String encoding)
            throws IOException {
        StringBuffer resultStr = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                entity.getContent(), encoding));
        String msg = null;
        while ((msg = br.readLine()) != null) {
            resultStr.append(msg);
        }
        return resultStr.toString();
    }

    public static String postUrlWithJson(String url, String json,
                                         String encoding) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuilder result = new StringBuilder();
        try {
            HttpPost post = new HttpPost(url);
            StringEntity se = new StringEntity(json, encoding);
            se.setContentType(new BasicHeader("Content-Type",
                    "application/json"));
            post.setEntity(se);
            HttpResponse httpResponse = httpClient.execute(post);
            int httpCode = httpResponse.getStatusLine().getStatusCode();

            if (httpCode == HttpURLConnection.HTTP_OK && httpResponse != null) {
                Header[] headers = httpResponse.getAllHeaders();
                HttpEntity entity = httpResponse.getEntity();
                Header header = httpResponse.getFirstHeader("content-type");
                // 读取服务器返回的json数据(接受json服务器数据)
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, encoding);
                BufferedReader reader = new BufferedReader(inputStreamReader);// 读字符串用的。
                String s;
                while (((s = reader.readLine()) != null)) {
                    result.append(s);
                }
                reader.close();// 关闭输入流
            } else {
                logger.warn("Error Response"
                        + httpResponse.getStatusLine().toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();// 最后关掉链接。
                httpClient = null;
            }
        }

        return result.toString();
    }


    /**
     * 传入JSON对象作为参数,并加上请求路径URL
     *
     * @param url
     * @param inputObject
     * @return
     */
    public static JSONObject postJSONCall(String url, JSONObject inputObject) {
        JSONObject result = null;
        try {
            String sendJson = inputObject.toString();
            String resultJson = postUrlWithJson(url, sendJson, "UTF-8");
            if ("".equals(resultJson)) {
                throw new ServiceException("调用接口返回为空串");
            }
            result = new JSONObject(resultJson);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException(e);
        }
        return result;
    }

//测试,传入json格式数据,返回json格式数据
    public static void main(String[] args) {
        String url = "http://localhost:7801/transfer/test";
        JSONObject object = new JSONObject();
        object.put("responseCode", "1");
        object.put("responseMsg", "1");
        JSONObject re = HttpUtil.postJSONCall(url, object);
        System.out.println(re);
    }
}
SSL工具类
/**
 * Author: hezishan
 * Date: 2018/5/11.
 * Description:SSLClient
 **/
public class SSLClient extends DefaultHttpClient {
    SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new    SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

StreamTool

/**
 * Author: hezishan
 * Date: 2018/5/11.
 * Description:StreamTool
 **/
public class StreamTool {
    /**
     * 从输入流中获取数据
     * @param inputStream 输入流
     * @return 字节数组
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inputStream) throws Exception
    {
        //实例化一个输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //一个1024字节的缓冲字节数组
        byte[] buffer = new byte[2048];
        int len = 0;
        //读流的基本知识
        while ((len=inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        //用完要关,大家都懂的
        inputStream.close();
        return outputStream.toByteArray();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值