org.apache.http.client.methods.CloseableHttpResponse.getEntity()

Here are the examples of the java api org.apache.http.client.methods.CloseableHttpResponse.getEntity() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1447 Examples 7

19 Source : WebHttpUtils.java
with MIT License
from Zo3i

public static String postJson(String url, String json) {
    String data = null;
    logger.debug(">>>请求地址:{},参数:{}", url, json);
    try {
        HttpPost httpPost = new HttpPost(url);
        StringEnreplacedy enreplacedy = new StringEnreplacedy(json, ENCODE);
        enreplacedy.setContentEncoding(ENCODE);
        enreplacedy.setContentType("application/json");
        httpPost.setEnreplacedy(enreplacedy);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEnreplacedy httpEnreplacedy = response.getEnreplacedy();
                data = EnreplacedyUtils.toString(httpEnreplacedy, ENCODE);
                logger.debug(">>>返回结果:{}", data);
                EnreplacedyUtils.consume(httpEnreplacedy);
            } else {
                httpPost.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}

19 Source : WebHttpUtils.java
with MIT License
from Zo3i

public static String post(String url, Map<String, String> nameValuePair) {
    String data = null;
    logger.debug(">>>请求地址:{},参数:{}", url, JSON.toJSONString(nameValuePair));
    try {
        HttpPost httpPost = new HttpPost(url);
        if (nameValuePair != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : nameValuePair.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(nvps, ENCODE));
        }
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                data = EnreplacedyUtils.toString(enreplacedy);
                logger.debug(">>>返回结果:{}", data);
                EnreplacedyUtils.consume(enreplacedy);
            } else {
                httpPost.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}

19 Source : WebHttpUtils.java
with MIT License
from Zo3i

public static String get(String url, Map<String, String> nameValuePair, Map<String, String> headers) {
    String data = null;
    logger.debug(">>>请求地址:{},参数:{}", url, JSON.toJSONString(nameValuePair));
    try {
        if (nameValuePair != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : nameValuePair.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            String queryStr = URLEncodedUtils.format(params, ENCODE);
            url = url + (url.contains("?") ? "&" : "?") + queryStr;
        }
        HttpGet httpGet = new HttpGet(url);
        if (headers != null) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                httpGet.addHeader(e.getKey(), e.getValue());
            }
        }
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                data = EnreplacedyUtils.toString(enreplacedy, ENCODE);
                logger.debug(">>>返回结果:{}", data);
                EnreplacedyUtils.consume(enreplacedy);
            } else {
                httpGet.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}

19 Source : WebHttpUtils.java
with MIT License
from Zo3i

public static byte[] getData(String url) {
    byte[] data = null;
    logger.debug(">>>请求地址:{}", url);
    try {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEnreplacedy enreplacedy = response.getEnreplacedy();
                data = EnreplacedyUtils.toByteArray(enreplacedy);
                EnreplacedyUtils.consume(enreplacedy);
            } else {
                httpGet.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}

19 Source : NetUtil.java
with Apache License 2.0
from zhugf

public static void readHttp(String httpUrl, HttpMethod method, String body, Charset charset, Map<String, String> props, OutputStream os) throws IOException {
    ContentType contentType = ContentType.APPLICATION_JSON;
    if (props != null && props.get("Content-Type") != null) {
        contentType = ContentType.parse(props.remove("Content-Type"));
    }
    if (charset == null) {
        charset = utf8Charset;
    }
    HttpClientContext context = currContet.get();
    if (context == null) {
        context = HttpClientContext.create();
        currContet.set(context);
    }
    HttpRequestBase req = null;
    switch(method) {
        case GET:
            req = new HttpGet(httpUrl);
            break;
        case POST:
            HttpPost post = new HttpPost(httpUrl);
            StringEnreplacedy postEnreplacedy = new StringEnreplacedy(body, contentType);
            post.setEnreplacedy(postEnreplacedy);
            req = post;
            break;
        case PUT:
            HttpPut put = new HttpPut(httpUrl);
            StringEnreplacedy putEnreplacedy = new StringEnreplacedy(body, contentType);
            put.setEnreplacedy(putEnreplacedy);
            req = put;
            break;
    }
    req.setHeader("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0");
    req.setHeader("Referer", httpUrl);
    if (props != null) {
        for (String key : props.keySet()) {
            req.setHeader(key, props.get(key));
        }
    }
    try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(true).build();
        CloseableHttpResponse response = httpClient.execute(req, context)) {
        lastStatus.set(response.getStatusLine().getStatusCode());
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        if (enreplacedy != null) {
            int totalLen = 0;
            InputStream is = enreplacedy.getContent();
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = is.read(data)) > 0) {
                os.write(data, 0, len);
                totalLen += len;
            }
            os.flush();
        }
    }
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhisheng17

/**
 * 通过GET方式发起http请求
 */
public static String doGet(String url) {
    HttpGet get = new HttpGet(url);
    get.setHeader("content-type", "application/json");
    // 如果要设置 Basic Auth 的话
    // get.setHeader("Authorization", getHeader());
    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(get);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
            if (null != enreplacedy) {
                return EnreplacedyUtils.toString(httpResponse.getEnreplacedy());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (httpResponse != null)
                httpResponse.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhisheng17

/**
 * 发送 POST 请求(HTTP),JSON形式
 *
 * @param url        调用的地址
 * @param jsonParams 调用的参数
 * @return
 * @throws Exception
 */
public static CloseableHttpResponse doPostResponse(String url, String jsonParams) throws Exception {
    CloseableHttpResponse response = null;
    HttpPost httpPost = new HttpPost(url);
    try {
        StringEnreplacedy enreplacedy = new StringEnreplacedy(jsonParams, "UTF-8");
        enreplacedy.setContentEncoding("UTF-8");
        enreplacedy.setContentType("application/json");
        httpPost.setEnreplacedy(enreplacedy);
        httpPost.setHeader("content-type", "application/json");
        // 如果要设置 Basic Auth 的话
        // httpPost.setHeader("Authorization", getHeader());
        response = httpClient.execute(httpPost);
    } finally {
        if (response != null) {
            EnreplacedyUtils.consume(response.getEnreplacedy());
        }
    }
    return response;
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhisheng17

public static String doPutString(String url, String jsonParams) throws Exception {
    CloseableHttpResponse response = null;
    HttpPut httpPut = new HttpPut(url);
    String httpStr;
    try {
        StringEnreplacedy enreplacedy = new StringEnreplacedy(jsonParams, "UTF-8");
        enreplacedy.setContentEncoding("UTF-8");
        enreplacedy.setContentType("application/json");
        httpPut.setEnreplacedy(enreplacedy);
        httpPut.setHeader("content-type", "application/json");
        // 如果要设置 Basic Auth 的话
        // httpPut.setHeader("Authorization", getHeader());
        response = httpClient.execute(httpPut);
        httpStr = EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
    } finally {
        if (response != null) {
            EnreplacedyUtils.consume(response.getEnreplacedy());
            response.close();
        }
    }
    return httpStr;
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhisheng17

public static String doPostString(String url, String jsonParams) throws Exception {
    CloseableHttpResponse response = null;
    HttpPost httpPost = new HttpPost(url);
    String httpStr;
    try {
        StringEnreplacedy enreplacedy = new StringEnreplacedy(jsonParams, "UTF-8");
        enreplacedy.setContentEncoding("UTF-8");
        enreplacedy.setContentType("application/json");
        httpPost.setEnreplacedy(enreplacedy);
        httpPost.setHeader("content-type", "application/json");
        // 如果要设置 Basic Auth 的话
        // httpPost.setHeader("Authorization", getHeader());
        response = httpClient.execute(httpPost);
        httpStr = EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
    } finally {
        if (response != null) {
            EnreplacedyUtils.consume(response.getEnreplacedy());
            response.close();
        }
    }
    return httpStr;
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhengjunbase

/**
 * 发送xml的post请求 指定contentType 和Charset
 *
 * @param url
 * @param xml
 * @param headers
 * @return
 */
@Nullable
public static String postXML(String url, String xml, ContentType contentType, final Charset charset, Header... headers) {
    CloseableHttpClient client = getHttpclient();
    HttpPost httpPost = new HttpPost(url);
    long start = System.currentTimeMillis();
    try {
        HttpEnreplacedy httpEnreplacedy = new StringEnreplacedy(xml, contentType);
        if (headers != null && headers.length > 0) {
            for (Header header : headers) {
                httpPost.addHeader(header);
            }
        }
        httpPost.setEnreplacedy(httpEnreplacedy);
        CloseableHttpResponse response = client.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            HttpEnreplacedy responseEnreplacedy = response.getEnreplacedy();
            return EnreplacedyUtils.toString(responseEnreplacedy, charset);
        }
    } catch (Exception e) {
        logger.error("push xml fail,url:{}", url, e);
    } finally {
        long cost = System.currentTimeMillis() - start;
        logger.info("httpUtil_postXml {}", cost);
        httpPost.releaseConnection();
    }
    return null;
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhengjunbase

public static HttpResult postJsonWithResult(String url, String body) {
    HttpPost httpPost = null;
    long start = System.currentTimeMillis();
    int code = 0;
    try {
        httpPost = new HttpPost(completeUrl(url));
        HttpEnreplacedy httpEnreplacedy = new StringEnreplacedy(body, APPLICATION_JSON_UTF8);
        httpPost.setEnreplacedy(httpEnreplacedy);
        httpPost.setHeader("Accept", "application/json");
        CloseableHttpResponse response = httpclient.execute(httpPost);
        code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            HttpEnreplacedy responseEnreplacedy = response.getEnreplacedy();
            String result = EnreplacedyUtils.toString(responseEnreplacedy, Consts.UTF_8);
            return new HttpResult(code, result);
        }
    } catch (IOException e) {
    } finally {
        long cost = System.currentTimeMillis() - start;
        if (null != httpPost) {
            httpPost.releaseConnection();
        }
    }
    return new HttpResult(code, "");
}

19 Source : HttpUtil.java
with Apache License 2.0
from zhengjunbase

/**
 * 发送xml的post请求
 *
 * @param url
 * @param xml
 * @param headers
 * @return
 */
@Nullable
public static String postXML(String url, String xml, Header... headers) {
    CloseableHttpClient client = getHttpclient();
    HttpPost httpPost = new HttpPost(url);
    long start = System.currentTimeMillis();
    try {
        HttpEnreplacedy httpEnreplacedy = new StringEnreplacedy(xml, HttpUtil.TEXT_XML_UTF8);
        if (headers != null && headers.length > 0) {
            for (Header header : headers) {
                httpPost.addHeader(header);
            }
        }
        httpPost.setEnreplacedy(httpEnreplacedy);
        CloseableHttpResponse response = client.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            HttpEnreplacedy responseEnreplacedy = response.getEnreplacedy();
            String result = EnreplacedyUtils.toString(responseEnreplacedy, Consts.UTF_8);
            return result;
        }
    } catch (Exception e) {
        logger.error("push xml fail,url:{}", url, e);
    } finally {
        long cost = System.currentTimeMillis() - start;
        logger.info("httpUtil_postXml {}", cost);
    }
    return null;
}

19 Source : ApplicationTests.java
with Eclipse Public License 1.0
from zhaoqilong3031

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    // HttpPost post = new HttpPost("http://localhost:8088/refresh");
    HttpPost post = new HttpPost("http://localhost:8888/bus/refresh");
    CloseableHttpResponse response = builder.build().execute(post);
    System.out.println(EnreplacedyUtils.toString(response.getEnreplacedy()));
}

19 Source : HttpClientDownloader.java
with MIT License
from zhangyd-c

@Override
public Page download(Request request, Task task) {
    if (task == null || task.getSite() == null) {
        throw new NullPointerException("task or site can not be null");
    }
    CloseableHttpResponse httpResponse = null;
    CloseableHttpClient httpClient = getHttpClient(task.getSite());
    Proxy proxy = proxyProvider != null ? proxyProvider.getProxy(task) : null;
    HttpClientRequestContext requestContext = httpUriRequestConverter.convert(request, task.getSite(), proxy);
    Page page = Page.fail();
    try {
        httpResponse = httpClient.execute(requestContext.getHttpUriRequest(), requestContext.getHttpClientContext());
        page = handleResponse(request, request.getCharset() != null ? request.getCharset() : task.getSite().getCharset(), httpResponse, task);
        onSuccess(request);
        logger.debug("downloading page success {}", request.getUrl());
        return page;
    } catch (IOException e) {
        logger.warn("download page {} error", request.getUrl(), e);
        onError(request);
        return page;
    } finally {
        if (httpResponse != null) {
            // ensure the connection is released back to pool
            EnreplacedyUtils.consumeQuietly(httpResponse.getEnreplacedy());
        }
        if (proxyProvider != null && proxy != null) {
            proxyProvider.returnProxy(proxy, page, task);
        }
    }
}

19 Source : HttpHelper.java
with Apache License 2.0
from Zephery

// public String get(String url, Map<String,String> headers, Proxy proxy, CookieStore cookieStore){
// if(null==url || "".equals(url)) {
// return null;
// }
// //创建httpclient请求方式
// HttpGet httpGet = new HttpGet("/");
// 
// CredentialsProvider credentialsProvider = null;
// HttpHost httpHost = new HttpHost(url);
// HttpHost proxyHost = null;
// AuthCache authCache = null;
// if(proxy != null) {
// proxyHost = new HttpHost(proxy.getHost(),proxy.getPort());
// credentialsProvider = new BasicCredentialsProvider();
// credentialsProvider.setCredentials(new AuthScope(proxy.getHost(),proxy.getPort()),
// //                    new UsernamePreplacedwordCredentials(proxy.getUserName(),proxy.getPreplacedWd()));
// credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePreplacedwordCredentials(proxy.getUserName(),proxy.getPreplacedWd()));
// //            authCache = new BasicAuthCache();
// //            BasicScheme basicScheme = new BasicScheme();
// //            authCache.put(targetHost,basicScheme);
// 
// }
// 
// 
// CloseableHttpResponse response = null;
// 
// httpGet.setHeader("Accept", "*/*");
// httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
// httpGet.setHeader("Connection", "keep-alive");
// httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36");
// 
// if(headers != null && headers.size() > 0) {
// for(String headName : headers.keySet()) {
// if(headName.toLowerCase().equals("cookie") || headName.toLowerCase().equals("user-agent")) {
// //cookie和userAgent用其它处理方式
// continue;
// }
// httpGet.setHeader(headName, headers.get(headName));
// }
// }
// 
// try {
// HttpContext httpContext = new BasicHttpContext();
// httpContext.setAttribute(HttpClientContext.COOKIE_SPEC, CookieSpecs.IGNORE_COOKIES);
// if(targetHost != null){
// httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER,credentialsProvider);
// //                httpContext.setAttribute(HttpClientContext.AUTH_CACHE,authCache);
// //                httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER,credentialsProvider);
// }
// if(cookieStore != null) {
// httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// } else {
// //				BasicCookieStore cookieStore = (BasicCookieStore)httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
// //				proxy.setCookieStore(cookieStore);
// BasicCookieStore basicCookieStore = new BasicCookieStore();
// httpContext.setAttribute(HttpClientContext.COOKIE_STORE, basicCookieStore);
// }
// 
// 
// 
// response = httpClient.execute(targetHost,httpGet, httpContext);
// 
// Header[] reHeaders = response.getAllHeaders();
// int statusCode = response.getStatusLine().getStatusCode();
// if(log.isDebugEnabled()) {
// log.debug("response code is =>"+statusCode);
// }
// HttpEnreplacedy enreplacedy = response.getEnreplacedy();
// String result = null;
// if (enreplacedy != null){
// result = EnreplacedyUtils.toString(enreplacedy, "utf-8");
// }
// EnreplacedyUtils.consume(enreplacedy);
// 
// if(cookieStore == null) {
// cookieStore = (BasicCookieStore)httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
// }
// response.close();
// return result;
// } catch(Exception e) {
// e.printStackTrace();
// return null;
// } finally{
// httpGet.releaseConnection();
// if(null != response){
// try {
// //关闭response
// response.close();
// } catch (IOException e) {
// // TODO 这里写异常处理的代码
// e.printStackTrace();
// }
// }
// }
// }
public String get(String url) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpContext httpContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet, httpContext);
        int statusCode = response.getStatusLine().getStatusCode();
        if (log.isDebugEnabled()) {
            log.debug("response code is =>" + statusCode);
            if (statusCode == 404) {
                System.out.println(url);
            }
        }
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = null;
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, "utf-8");
        }
        EnreplacedyUtils.consume(enreplacedy);
        response.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        httpGet.releaseConnection();
        if (null != response) {
            try {
                // 关闭response
                response.close();
            } catch (IOException e) {
                // TODO 这里写异常处理的代码
                e.printStackTrace();
            }
        }
    }
}

19 Source : HttpHelper.java
with Apache License 2.0
from Zephery

/**
 * HTTP Post 获取内容
 *
 * @param url     请求的url地址 ?之前的地址
 * @param params  请求的参数
 * @param charset 编码格式
 * @return 页面内容
 */
public String doPost(String url, Map<String, String> params, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    log.info(" post url=" + url);
    try {
        List<NameValuePair> pairs = null;
        if (params != null && !params.isEmpty()) {
            pairs = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String value = entry.getValue();
                if (value != null) {
                    pairs.add(new BasicNameValuePair(entry.getKey(), value));
                }
            }
        }
        HttpPost httpPost = new HttpPost(url);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(pairs, charset));
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = null;
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, charset);
        }
        EnreplacedyUtils.consume(enreplacedy);
        response.close();
        return result;
    } catch (Exception e) {
        log.error("to request addr=" + url + ", " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

19 Source : HttpHelper.java
with Apache License 2.0
from Zephery

public Integer getStatusCode(String url) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    HttpContext httpContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet, httpContext);
        int statusCode = response.getStatusLine().getStatusCode();
        if (log.isDebugEnabled()) {
            log.debug("response code is =>" + statusCode);
            if (statusCode == 404) {
                System.out.println(url);
            }
            if (statusCode == 400) {
                return statusCode;
            }
        }
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = null;
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, "utf-8");
        }
        EnreplacedyUtils.consume(enreplacedy);
        response.close();
        return statusCode;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        httpGet.releaseConnection();
        if (null != response) {
            try {
                // 关闭response
                response.close();
            } catch (IOException e) {
                // TODO 这里写异常处理的代码
                e.printStackTrace();
            }
        }
    }
}

19 Source : HttpHelper.java
with Apache License 2.0
from Zephery

public String doPost(String url, List<NameValuePair> pairs, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    log.info(" post url=" + url);
    try {
        HttpPost httpPost = new HttpPost(url);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(pairs, charset));
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = null;
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, charset);
        }
        EnreplacedyUtils.consume(enreplacedy);
        response.close();
        return result;
    } catch (Exception e) {
        log.error("to request addr=" + url + ", " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

19 Source : HttpHelper.java
with Apache License 2.0
from Zephery

public String doPostLongWait(String url, List<NameValuePair> pairs, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    log.info(" post url=" + url);
    try {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300000).setConnectTimeout(30000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        if (pairs != null && pairs.size() > 0) {
            httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(pairs, charset));
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = null;
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, charset);
        }
        EnreplacedyUtils.consume(enreplacedy);
        response.close();
        return result;
    } catch (Exception e) {
        log.error("to request addr=" + url + ", " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}

19 Source : HttpService.java
with Apache License 2.0
from Zephery

/**
 * @param url
 * @param params 请求中的参数
 * @return 请求到的内容
 * @throws URISyntaxException
 * @throws ClientProtocolException
 * @throws IOException
 */
public String doPost(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {
    // 设置post参数
    List<NameValuePair> parameters = null;
    // 构造一个form表单式的实体
    UrlEncodedFormEnreplacedy formEnreplacedy = null;
    // 定义请求的参数
    if (params != null) {
        // 设置post参数
        parameters = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            // 添加参数
            parameters.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
        }
        // 构造一个form表单式的实体
        formEnreplacedy = new UrlEncodedFormEnreplacedy(parameters);
    }
    // 创建http GET请求
    HttpPost httpPost = null;
    if (formEnreplacedy != null) {
        httpPost = new HttpPost(url);
        // 将请求实体设置到httpPost对象中
        httpPost.setEnreplacedy(formEnreplacedy);
        // 伪装浏览器请求
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
    } else {
        httpPost = new HttpPost(url);
        // 伪装浏览器请求
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
    }
    // 设置请求参数
    httpPost.setConfig(this.requestConfig);
    // 请求的结果
    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = httpClient.execute(httpPost);
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取服务端返回的数据,并返回
            return EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpService.java
with Apache License 2.0
from Zephery

/**
 * 执行Get请求
 *
 * @param url
 * @param params 请求中的参数
 * @return 请求到的内容
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 */
public String doGet(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {
    // 定义请求的参数
    URI uri = null;
    if (params != null) {
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
        }
        uri = builder.build();
    }
    // 创建http GET请求
    HttpGet httpGet = null;
    if (uri != null) {
        httpGet = new HttpGet(uri);
    } else {
        httpGet = new HttpGet(url);
    }
    // 设置请求参数
    httpGet.setConfig(this.requestConfig);
    // 请求的结果
    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = httpClient.execute(httpGet);
        // 判断返回状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取服务端返回的数据,并返回
            return EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
        }
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpUtil.java
with Apache License 2.0
from yz-java

public static String sendPostFile(String url, File file, Map<String, String> data) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    MultipartEnreplacedyBuilder multipartEnreplacedyBuilder = MultipartEnreplacedyBuilder.create();
    multipartEnreplacedyBuilder.setCharset(Charset.forName("UTF-8"));
    multipartEnreplacedyBuilder.addBinaryBody("file", file);
    if (data != null) {
        data.forEach((k, v) -> {
            multipartEnreplacedyBuilder.addTextBody(k, v);
        });
    }
    HttpEnreplacedy httpEnreplacedy = multipartEnreplacedyBuilder.build();
    httpPost.setEnreplacedy(httpEnreplacedy);
    try {
        CloseableHttpResponse response = httpClient.execute(httpPost);
        return EnreplacedyUtils.toString(response.getEnreplacedy());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

19 Source : AbstractHttpClientMockTests.java
with Apache License 2.0
from yuanmabiji

protected HttpEnreplacedy mockHttpEnreplacedy(CloseableHttpResponse response, byte[] content, String contentType) {
    try {
        HttpEnreplacedy enreplacedy = mock(HttpEnreplacedy.clreplaced);
        given(enreplacedy.getContent()).willReturn(new ByteArrayInputStream(content));
        Header contentTypeHeader = (contentType != null) ? new BasicHeader("Content-Type", contentType) : null;
        given(enreplacedy.getContentType()).willReturn(contentTypeHeader);
        given(response.getEnreplacedy()).willReturn(enreplacedy);
        return enreplacedy;
    } catch (IOException ex) {
        throw new IllegalStateException("Should not happen", ex);
    }
}

19 Source : InitializrService.java
with Apache License 2.0
from yuanmabiji

/**
 * Load the {@link InitializrServiceMetadata} at the specified url.
 * @param serviceUrl to url of the initializer service
 * @return the metadata describing the service
 * @throws IOException if the service's metadata cannot be loaded
 */
public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException {
    CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl);
    validateResponse(httpResponse, serviceUrl);
    return parseJsonMetadata(httpResponse.getEnreplacedy());
}

19 Source : InitializrService.java
with Apache License 2.0
from yuanmabiji

/**
 * Generate a project based on the specified {@link ProjectGenerationRequest}.
 * @param request the generation request
 * @return an enreplacedy defining the project
 * @throws IOException if generation fails
 */
public ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException {
    Log.info("Using service at " + request.getServiceUrl());
    InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl());
    URI url = request.generateUrl(metadata);
    CloseableHttpResponse httpResponse = executeProjectGenerationRequest(url);
    HttpEnreplacedy httpEnreplacedy = httpResponse.getEnreplacedy();
    validateResponse(httpResponse, request.getServiceUrl());
    return createResponse(httpResponse, httpEnreplacedy);
}

19 Source : InitializrService.java
with Apache License 2.0
from yuanmabiji

private ReportableException createException(String url, CloseableHttpResponse httpResponse) {
    String message = "Initializr service call failed using '" + url + "' - service returned " + httpResponse.getStatusLine().getReasonPhrase();
    String error = extractMessage(httpResponse.getEnreplacedy());
    if (StringUtils.hasText(error)) {
        message += ": '" + error + "'";
    } else {
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        message += " (unexpected " + statusCode + " error)";
    }
    throw new ReportableException(message);
}

19 Source : InitializrService.java
with Apache License 2.0
from yuanmabiji

/**
 * Loads the service capabilities of the service at the specified URL. If the service
 * supports generating a textual representation of the capabilities, it is returned,
 * otherwise {@link InitializrServiceMetadata} is returned.
 * @param serviceUrl to url of the initializer service
 * @return the service capabilities (as a String) or the
 * {@link InitializrServiceMetadata} describing the service
 * @throws IOException if the service capabilities cannot be loaded
 */
public Object loadServiceCapabilities(String serviceUrl) throws IOException {
    HttpGet request = new HttpGet(serviceUrl);
    request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES));
    CloseableHttpResponse httpResponse = execute(request, serviceUrl, "retrieve help");
    validateResponse(httpResponse, serviceUrl);
    HttpEnreplacedy httpEnreplacedy = httpResponse.getEnreplacedy();
    ContentType contentType = ContentType.getOrDefault(httpEnreplacedy);
    if (contentType.getMimeType().equals("text/plain")) {
        return getContent(httpEnreplacedy);
    }
    return parseJsonMetadata(httpEnreplacedy);
}

19 Source : HttpRequest.java
with Apache License 2.0
from yjjdick

public synchronized static String postData(String url) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String result = "";
    try {
        StatusLine statusLine = response.getStatusLine();
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        // do something useful with the response body
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
        } else {
            LogKit.error("httpRequest postData2 error enreplacedy = null code = " + statusLine.getStatusCode());
        }
        // and ensure it is fully consumed
        // 消耗掉response
        EnreplacedyUtils.consume(enreplacedy);
    } finally {
        response.close();
    }
    return result;
}

19 Source : HttpRequest.java
with Apache License 2.0
from yjjdick

public synchronized static String postData(String url, Map<String, String> params) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    // 拼接参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    NameValuePair[] nameValuePairArray = replacedembleRequestParams(params);
    for (NameValuePair value : nameValuePairArray) {
        nvps.add(value);
    }
    httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(nvps, "UTF-8"));
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String result = "";
    try {
        StatusLine statusLine = response.getStatusLine();
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        // do something useful with the response body
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
        } else {
            LogKit.error("httpRequest postData1 error enreplacedy = null code = " + statusLine.getStatusCode());
        }
        // and ensure it is fully consumed
        // 消耗掉response
        EnreplacedyUtils.consume(enreplacedy);
    } finally {
        response.close();
    }
    return result;
}

19 Source : LianlianClient.java
with Apache License 2.0
from yi-jun

public String sendHttpPost(String url, String str) throws HttpClientException {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        LianlianSreplacedils.ignoreSsl();
    } catch (Exception e1) {
        logger.error("Sreplacedils异常", e1);
    }
    try {
        if (logger.isDebugEnabled())
            logger.debug(" send http start ");
        if (StringUtils.isBlank(url))
            throw new HttpClientException(" sendHttpPost exception,url is blank.");
        Charset charset = Charset.forName("UTF-8");
        httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url.trim());
        StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(str, charset);
        httpPost.setConfig(this.getCustomConfig());
        httpPost.setEnreplacedy(stringEnreplacedy);
        response = httpclient.execute(httpPost);
        if (logger.isDebugEnabled())
            logger.debug(" send http execute status is: " + response.getStatusLine());
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String resultXml = EnreplacedyUtils.toString(enreplacedy, charset);
        EnreplacedyUtils.consume(enreplacedy);
        if (logger.isDebugEnabled())
            logger.debug(" send request end ");
        return resultXml != null && !"".equals(resultXml) ? resultXml : "";
    } catch (Exception e) {
        logger.error("sendHttpPost exception:", e);
        throw new HttpClientException(" sendHttpPost exception:", e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("sendHttpPost response close IOException:", e);
            }
        }
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("sendHttpPost httpclient close IOException:", e);
            }
        }
    }
}

19 Source : HttpClientHelper.java
with Apache License 2.0
from yi-jun

public String sendBaofoo(String url, Map<String, String> map) throws HttpClientException {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        if (logger.isDebugEnabled())
            logger.debug(" send http start ");
        Charset charset = Charset.forName("UTF-8");
        SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
        httpclient = HttpClients.custom().setConnectionManager(cm).build();
        HttpPost httpPost = new HttpPost(url.trim());
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : map.entrySet()) nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        UrlEncodedFormEnreplacedy urlEncodedFormEnreplacedy = new UrlEncodedFormEnreplacedy(nvps, charset);
        // 三个参数依次为 请求超时时间 链接超时时间 数据响应超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setEnreplacedy(urlEncodedFormEnreplacedy);
        // 执行请求,得到响应对象
        response = httpclient.execute(httpPost);
        if (logger.isDebugEnabled())
            logger.debug(" send http execute status is: " + response.getStatusLine());
        // 得到响应实体
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        // 转换成字符串
        String resultXml = EnreplacedyUtils.toString(enreplacedy, charset);
        // 检查是否读取完毕
        EnreplacedyUtils.consume(enreplacedy);
        if (logger.isDebugEnabled())
            logger.debug(" send http end ");
        return resultXml != null && !"".equals(resultXml) ? resultXml : "";
    } catch (Exception e) {
        logger.error("sendHttpPost exception:", e);
        throw new HttpClientException(" sendHttpPost exception: ", e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("sendHttpPost response close IOException:", e);
            }
        }
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("sendHttpPost httpclient close IOException:", e);
            }
        }
    }
}

19 Source : HttpClientHelper.java
with Apache License 2.0
from yi-jun

/**
 * 发送http get请求
 *
 * @param url
 *            请求地址
 * @param charset
 *            请求/响应字符编码
 * @return 响应结果
 */
public String sendHttpGet(String url, Charset charset) throws HttpClientException {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        if (logger.isDebugEnabled())
            logger.debug(" send http start ");
        if (StringUtils.isBlank(url))
            throw new HttpClientException(" sendHttpGet exception,url is blank.");
        if (charset == null)
            charset = Charset.forName("UTF-8");
        httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url.trim());
        httpget.setConfig(this.getCustomConfig());
        response = httpclient.execute(httpget);
        if (logger.isDebugEnabled())
            logger.debug(" send http execute status is: " + response.getStatusLine());
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String resultXml = EnreplacedyUtils.toString(enreplacedy, charset);
        EnreplacedyUtils.consume(enreplacedy);
        if (logger.isDebugEnabled())
            logger.debug(" send request end ");
        return resultXml != null && !"".equals(resultXml) ? resultXml : "";
    } catch (Exception e) {
        logger.error("sendHttpGet exception:", e);
        throw new HttpClientException(" sendHttpGet exception:", e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("sendHttpGet response close IOException:", e);
            }
        }
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("sendHttpGet httpclient close IOException:", e);
            }
        }
    }
}

19 Source : HttpClientHelper.java
with Apache License 2.0
from yi-jun

/**
 * 发送httpPost请求,请内容为map集合(需指定key-value)
 *
 * @param url
 *            请求地址
 * @param charset
 *            请求/响应字符编码
 * @param map
 *            参数列表
 * @return 响应结果
 */
public String sendHttpPost(String url, Charset charset, Map<String, String> map) throws HttpClientException {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        if (logger.isDebugEnabled())
            logger.debug(" send http start ");
        if (StringUtils.isBlank(url))
            throw new HttpClientException(" sendHttpPost exception,url is blank.");
        if (charset == null)
            charset = Charset.forName("UTF-8");
        httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url.trim());
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : map.entrySet()) nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        UrlEncodedFormEnreplacedy urlEncodedFormEnreplacedy = new UrlEncodedFormEnreplacedy(nvps, charset);
        httpPost.setConfig(this.getCustomConfig());
        httpPost.setEnreplacedy(urlEncodedFormEnreplacedy);
        // 执行请求,得到响应对象
        response = httpclient.execute(httpPost);
        if (logger.isDebugEnabled())
            logger.debug(" send http execute status is: " + response.getStatusLine());
        // 得到响应实体
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        // 转换成字符串
        String resultXml = EnreplacedyUtils.toString(enreplacedy, charset);
        // 检查是否读取完毕
        EnreplacedyUtils.consume(enreplacedy);
        if (logger.isDebugEnabled())
            logger.debug(" send http end ");
        return resultXml != null && !"".equals(resultXml) ? resultXml : "";
    } catch (Exception e) {
        logger.error("sendHttpPost exception:", e);
        throw new HttpClientException(" sendHttpPost exception: ", e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                logger.error("sendHttpPost response close IOException:", e);
            }
        }
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("sendHttpPost httpclient close IOException:", e);
            }
        }
    }
}

19 Source : HttpUtil.java
with Apache License 2.0
from yeecode

private synchronized String sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url);
        StringEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(nameValuePairList, "UTF-8");
        post.setEnreplacedy(enreplacedy);
        post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
        post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            return EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
        }
    } catch (Exception e) {
        LOGGER.error("send post error", e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientBean.java
with Apache License 2.0
from yeecode

private synchronized Result sendPost(String url, List<NameValuePair> nameValuePairList) {
    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url);
        StringEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(nameValuePairList, "UTF-8");
        post.setEnreplacedy(enreplacedy);
        post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
        post.setHeader(new BasicHeader("Accept", "text/html, application/xhtml+xml, application/json"));
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        String result = EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
        if (200 == statusCode) {
            return ResultUtil.getSuccessResult(result);
        } else {
            return ResultUtil.getFailResult("statusCode:" + statusCode, result);
        }
    } catch (Exception e) {
        LOGGER.error("send post error", e);
        return ResultUtil.getFailResult("error", e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception ex) {
                LOGGER.error("close response error", ex);
            }
        }
    }
}

19 Source : HttpUtil.java
with Apache License 2.0
from yeecode

private static synchronized String sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url);
        StringEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(nameValuePairList, "UTF-8");
        post.setEnreplacedy(enreplacedy);
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            return EnreplacedyUtils.toString(response.getEnreplacedy(), "UTF-8");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from yanghaiji

/**
 * 发送post请求,参数用map接收
 *
 * @param url 地址
 * @param map 参数
 * @return 返回值
 */
public static String postMap(String url, Map<String, String> map) {
    String result = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    CloseableHttpResponse response = null;
    try {
        post.setEnreplacedy(new UrlEncodedFormEnreplacedy(pairs, utf));
        response = httpClient.execute(post);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            result = enreplacedyToString(enreplacedy);
        }
        return result;
    } catch (UnsupportedEncodingException e) {
        log.info(e.getMessage());
    } catch (ClientProtocolException e) {
        log.info(e.getMessage());
    } catch (IOException e) {
        log.info(e.getMessage());
    } finally {
        try {
            httpClient.close();
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }
    return null;
}

19 Source : JsonUtil.java
with GNU Affero General Public License v3.0
from xy-Group

public static JSONObject readJSONObjectFromUrl(String url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        if (enreplacedy != null) {
            String resultBody = EnreplacedyUtils.toString(enreplacedy, "utf-8");
            JSONObject json = new JSONObject(resultBody);
            return json;
        }
    } catch (IOException e) {
        return null;
    } finally {
        try {
            response.close();
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

19 Source : JsonUtil.java
with GNU Affero General Public License v3.0
from xy-Group

public static JSONArray readJsonsFromUrl(String url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        if (enreplacedy != null) {
            String resultBody = EnreplacedyUtils.toString(enreplacedy, "utf-8");
            JSONArray jsons = new JSONArray(resultBody);
            return jsons;
        }
    } catch (IOException e) {
        return null;
    } finally {
        try {
            response.close();
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

19 Source : ClientConnectionRelease.java
with GNU Affero General Public License v3.0
from xy-Group

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet("http://httpbin.org/get");
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // Get hold of the response enreplacedy
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            if (enreplacedy != null) {
                // 打印响应内容长度
                System.out.println("Response content length: " + enreplacedy.getContentLength());
                // 打印响应内容
                System.out.println("Response content: " + EnreplacedyUtils.toString(enreplacedy));
            }
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

19 Source : ClientConnectionRelease.java
with GNU Affero General Public License v3.0
from xy-Group

public static JSONArray readJsonsFromUrl(String url) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        if (enreplacedy != null) {
            String resultBody = EnreplacedyUtils.toString(enreplacedy);
            JSONArray jsons = new JSONArray(resultBody);
            return jsons;
        }
    } catch (IOException e) {
        return null;
    } finally {
        try {
            response.close();
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return null;
}

19 Source : HttpUtil.java
with GNU General Public License v3.0
from xxxgod

/**
 * 发送HttpPost请求,参数为map
 * @param url 请求地址
 * @param map 请求参数
 * @return 返回字符串
 */
public static String sendPost(String url, Map<String, String> map) {
    // 设置参数
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : map.entrySet()) {
        formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    // 编码
    UrlEncodedFormEnreplacedy formEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, Consts.UTF_8);
    // 取得HttpPost对象
    HttpPost httpPost = new HttpPost(url);
    // 防止被当成攻击添加的
    httpPost.setHeader("User-Agent", userAgent);
    // 参数放入Enreplacedy
    httpPost.setEnreplacedy(formEnreplacedy);
    CloseableHttpResponse response = null;
    String result = null;
    try {
        // 执行post请求
        response = httpclient.execute(httpPost);
        // 得到enreplacedy
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        // 得到字符串
        result = EnreplacedyUtils.toString(enreplacedy);
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
    return result;
}

19 Source : HttpUtil.java
with GNU General Public License v3.0
from xxxgod

/**
 * 发送HttpGet请求
 * @param url 请求地址
 * @return 返回字符串
 */
public static String sendGet(String url) {
    String result = null;
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("User-Agent", userAgent);
        response = httpclient.execute(httpGet);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        if (enreplacedy != null) {
            result = EnreplacedyUtils.toString(enreplacedy);
        }
    } catch (Exception e) {
        log.error("处理失败," + e);
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
    return result;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * http的post请求(用于请求json格式的参数)
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String doHttpPost(String url, String jsonStr, Map<String, String> headerPram) throws ClientProtocolException, IOException {
    try {
        httpClient = HttpClients.createDefault();
        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        StringEnreplacedy enreplacedy = new StringEnreplacedy(jsonStr, charSet);
        enreplacedy.setContentType("text/json");
        enreplacedy.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        httpPost.setEnreplacedy(enreplacedy);
        // 发送post请求
        response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEnreplacedy responseEnreplacedy = response.getEnreplacedy();
            String jsonString = EnreplacedyUtils.toString(responseEnreplacedy);
            return jsonString;
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * http的post请求(用于key-value格式的参数)
 * @param url
 * @param param
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String doHttpsPost(String url, Map<String, String> param, Map<String, String> headerPram) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    try {
        // 请求发起客户端
        httpClient = SSLClient.createSSLClientDefault();
        // 参数集合
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        // 遍历参数并添加到集合
        for (Map.Entry<String, String> entry : param.entrySet()) {
            postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 通过post方式访问
        HttpPost post = new HttpPost(url);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        HttpEnreplacedy paramEnreplacedy = new UrlEncodedFormEnreplacedy(postParams, charSet);
        post.setEnreplacedy(paramEnreplacedy);
        response = httpClient.execute(post);
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        if (state == HttpStatus.SC_OK) {
            HttpEnreplacedy valueEnreplacedy = response.getEnreplacedy();
            String content = EnreplacedyUtils.toString(valueEnreplacedy);
            // jsonObject = JSONObject.fromObject(content);
            return content;
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * http的Get请求
 * @param url
 * @param param
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String doHttpGet(String url, Map<String, String> param, Map<String, String> headerPram) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        httpclient = HttpClients.createDefault();
        if (param != null && !param.isEmpty()) {
            // 参数集合
            List<NameValuePair> getParams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                getParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            url += "?" + EnreplacedyUtils.toString(new UrlEncodedFormEnreplacedy(getParams), "UTF-8");
        }
        // 发送gey请求
        HttpGet httpGet = new HttpGet(url);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EnreplacedyUtils.toString(response.getEnreplacedy());
        }
    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * https的post请求
 * @param url
 * @param jsonstr
 * @param charset
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String doHttpsPost(String url, String jsonStr, Map<String, String> headerPram) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    try {
        httpClient = SSLClient.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        StringEnreplacedy se = new StringEnreplacedy(jsonStr);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        httpPost.setEnreplacedy(se);
        response = httpClient.execute(httpPost);
        if (response != null) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (resEnreplacedy != null) {
                return EnreplacedyUtils.toString(resEnreplacedy, charSet);
            }
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * https的Get请求
 * @param url
 * @param param
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String doHttpsGet(String url, Map<String, String> param, Map<String, String> headerPram) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    try {
        httpClient = SSLClient.createSSLClientDefault();
        if (param != null && !param.isEmpty()) {
            // 参数集合
            List<NameValuePair> getParams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                getParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            url += "?" + EnreplacedyUtils.toString(new UrlEncodedFormEnreplacedy(getParams), "UTF-8");
        }
        HttpGet httpGet = new HttpGet(url);
        RequestConfig rconfig = RequestConfig.custom().setConnectionRequestTimeout(2000).setSocketTimeout(4000).setConnectTimeout(3000).build();
        httpGet.setConfig(rconfig);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        response = httpClient.execute(httpGet);
        if (response != null) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (resEnreplacedy != null) {
                return EnreplacedyUtils.toString(resEnreplacedy, charSet);
            }
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }
    return null;
}

19 Source : HttpClientUtil.java
with Apache License 2.0
from xunibidev

/**
 * http的post请求(用于key-value格式的参数)
 * @param url
 * @param param
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static String doHttpPost(String url, Map<String, String> param, Map<String, String> headerPram) throws ClientProtocolException, IOException {
    try {
        // 请求发起客户端
        httpClient = HttpClients.createDefault();
        // 参数集合
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        // 遍历参数并添加到集合
        for (Map.Entry<String, String> entry : param.entrySet()) {
            postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 通过post方式访问
        HttpPost post = new HttpPost(url);
        if (headerPram != null && !headerPram.isEmpty()) {
            for (Map.Entry<String, String> entry : headerPram.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        HttpEnreplacedy paramEnreplacedy = new UrlEncodedFormEnreplacedy(postParams, charSet);
        post.setEnreplacedy(paramEnreplacedy);
        response = httpClient.execute(post);
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        if (state == HttpStatus.SC_OK) {
            HttpEnreplacedy valueEnreplacedy = response.getEnreplacedy();
            String content = EnreplacedyUtils.toString(valueEnreplacedy);
            return content;
        } else {
            return null;
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
    }
}

19 Source : FeigeSMSProvider.java
with Apache License 2.0
from xunibidev

/**
 * 发送单条短信
 *
 * @param mobile  手机号
 * @param content 短信内容
 * @return
 * @throws Exception
 */
@Override
public MessageResult sendSingleMessage(String mobile, String content) throws Exception {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
        List<BasicNameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("Account", username));
        formparams.add(new BasicNameValuePair("Pwd", preplacedword));
        formparams.add(new BasicNameValuePair("Content", content));
        formparams.add(new BasicNameValuePair("Mobile", mobile));
        formparams.add(new BasicNameValuePair("SignId", "ǩ��id"));
        HttpPost httpPost = new HttpPost("http://api.feige.ee/SmsService/Send");
        httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(formparams, "UTF-8"));
        client = HttpClients.createDefault();
        response = client.execute(httpPost);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        String result = EnreplacedyUtils.toString(enreplacedy);
        System.out.println(result);
    } finally {
        if (response != null) {
            response.close();
        }
        if (client != null) {
            client.close();
        }
    }
    return null;
}

See More Examples