org.apache.http.HttpEntity.getContentType()

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

69 Examples 7

19 Source : HttpClientInterceptorTests.java
with Apache License 2.0
from vividus-framework

@Test
void testHttpRequestBodyAttachingIsFailed() throws IOException {
    HttpEnreplacedy httpEnreplacedy = mock(HttpEnreplacedy.clreplaced);
    when(httpEnreplacedy.getContentType()).thenReturn(null);
    IOException ioException = new IOException();
    doThrow(ioException).when(httpEnreplacedy).writeTo(any(ByteArrayOutputStream.clreplaced));
    HttpEnreplacedyEnclosingRequest httpRequest = mockHttpEnreplacedyEnclosingRequest(new Header[] { mock(Header.clreplaced) }, httpEnreplacedy);
    testNoHttpRequestBodyIsAttached(httpRequest, equalTo(List.of(error(ioException, "Error is occurred at HTTP message parsing"))));
}

19 Source : HttpClientInterceptorTests.java
with Apache License 2.0
from vividus-framework

private void testHttpRequestIsAttachedSuccessfully(Header[] allRequestHeaders, Header enreplacedyContentTypeHeader) throws IOException {
    HttpEnreplacedy httpEnreplacedy = mock(HttpEnreplacedy.clreplaced);
    when(httpEnreplacedy.getContentType()).thenReturn(enreplacedyContentTypeHeader);
    HttpEnreplacedyEnclosingRequest httpRequest = mockHttpEnreplacedyEnclosingRequest(allRequestHeaders, httpEnreplacedy);
    testHttpRequestIsAttachedSuccessfully(httpRequest);
    verify(httpEnreplacedy).getContentLength();
    verify(httpEnreplacedy).writeTo(any(ByteArrayOutputStream.clreplaced));
}

19 Source : TestTdsDodsServer.java
with BSD 3-Clause "New" or "Revised" License
from Unidata

@Test
public void testTooBigAscii() throws IOException {
    String endpoint = TestOnLocalServer.withHttpPath("dodsC/HRRR/replacedysis/TP.ascii?u-component_of_wind_isobaric&Temperature_isobaric&v-component_of_wind_isobaric");
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(endpoint);
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine status = response.getStatusLine();
        replacedert.replacedertEquals(status.getStatusCode(), 403);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        replacedert.replacedertEquals(enreplacedy.getContentType().getValue(), MediaType.TEXT_PLAIN.toString());
        String responseString = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
        replacedert.replacedertTrue(responseString.toLowerCase().contains("request too large"));
    }
}

19 Source : TestTdsDodsServer.java
with BSD 3-Clause "New" or "Revised" License
from Unidata

@Test
public void testTooBigDods() throws IOException {
    String endpoint = TestOnLocalServer.withHttpPath("dodsC/HRRR/replacedysis/TP.dods?u-component_of_wind_isobaric&Temperature_isobaric&v-component_of_wind_isobaric");
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(endpoint);
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine status = response.getStatusLine();
        replacedert.replacedertEquals(status.getStatusCode(), 403);
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        replacedert.replacedertEquals(enreplacedy.getContentType().getValue(), MediaType.TEXT_PLAIN.toString());
        String responseString = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
        replacedert.replacedertTrue(responseString.toLowerCase().contains("request too large"));
    }
}

19 Source : HttpSendClient.java
with Apache License 2.0
from ucarGroup

private String uncompress(HttpResponse httpResponse) throws ParseException, IOException {
    int ret = httpResponse.getStatusLine().getStatusCode();
    if (!isOK(ret)) {
        return null;
    }
    // Read the contents
    String respBody = null;
    HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
    String charset = EnreplacedyUtils.getContentCharSet(enreplacedy);
    if (charset == null) {
        charset = "UTF-8";
    }
    // "Content-Encoding"
    Header contentEncodingHeader = enreplacedy.getContentEncoding();
    if (contentEncodingHeader != null) {
        String contentEncoding = contentEncodingHeader.getValue();
        if (contentEncoding.contains("gzip")) {
            respBody = EnreplacedyUtils.toString(new GzipDecompressingEnreplacedy(enreplacedy), charset);
        } else if (contentEncoding.contains("deflate")) {
            respBody = EnreplacedyUtils.toString(new DeflateDecompressingEnreplacedy(enreplacedy), charset);
        }
    } else {
        // "Content-Type"
        Header contentTypeHeader = enreplacedy.getContentType();
        if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null) {
                if (contentType.startsWith("application/x-gzip-compressed")) {
                    respBody = EnreplacedyUtils.toString(new GzipDecompressingEnreplacedy(enreplacedy), charset);
                } else if (contentType.startsWith("application/x-deflate")) {
                    respBody = EnreplacedyUtils.toString(new DeflateDecompressingEnreplacedy(enreplacedy), charset);
                }
            }
        }
    }
    return respBody;
}

19 Source : P2ProxyIT.java
with Eclipse Public License 1.0
from sonatype-nexus-community

private static InputStream openMetadata(final HttpEnreplacedy enreplacedy) throws Exception {
    String contentType = enreplacedy.getContentType().getValue();
    if (contentType.contains(XML_MIME_TYPE)) {
        return enreplacedy.getContent();
    } else if (contentType.contains(XZ_MIME_TYPE)) {
        return new XZInputStream(enreplacedy.getContent());
    } else if (contentType.contains(JAR_MIME_TYPE)) {
        ZipInputStream in = new ZipInputStream(enreplacedy.getContent());
        in.getNextEntry();
        return in;
    }
    fail("Unexpected mimetype " + contentType);
    return null;
}

19 Source : AbstractHttpSender.java
with MIT License
from ria-ee

protected String getResponseContentType(HttpEnreplacedy enreplacedy, boolean isGetRequest) {
    Header contentType = enreplacedy.getContentType();
    if (contentType == null) {
        if (isGetRequest) {
            return null;
        }
        throw new CodedException(X_INVALID_CONTENT_TYPE, "Could not get content type from response");
    }
    return contentType.getValue();
}

19 Source : BufferedJestHttpClientTest.java
with Apache License 2.0
from rfoltyns

@Test
public void prepareRequestCreatesRequestWithContentTypeHeader() throws IOException {
    // given
    BufferedBulk bulk = createDefaultTestBufferedBulk();
    // when
    BufferedJestHttpClient client = createDefaultTestHttpClient();
    HttpUriRequest request = client.prepareRequest(bulk);
    // then
    HttpEnreplacedy enreplacedy = ((HttpEnreplacedyEnclosingRequest) request).getEnreplacedy();
    replacedert.replacedertEquals(ContentType.APPLICATION_JSON.toString(), enreplacedy.getContentType().getValue());
}

19 Source : HttpClientTest.java
with Apache License 2.0
from rfoltyns

@Test
public void createClientRequestCreatesRequestWithContentTypeHeader() throws IOException {
    // given
    BatchRequest request = createDefaultTestBatchRequest();
    // when
    HttpClient client = createDefaultTestObject();
    HttpUriRequest httpRequest = client.createClientRequest(request);
    // then
    HttpEnreplacedy enreplacedy = ((HttpEnreplacedyEnclosingRequest) httpRequest).getEnreplacedy();
    replacedert.replacedertEquals(ContentType.APPLICATION_JSON.toString(), enreplacedy.getContentType().getValue());
}

19 Source : AopHttpEntity.java
with Apache License 2.0
from Qihoo360

@Override
public Header getContentType() {
    return mHttpEnreplacedy.getContentType();
}

19 Source : MarcElasticsearchClientTest.java
with GNU General Public License v3.0
from pkiraly

// @Test
public void testElasticsearchRunning() throws IOException {
    MarcElasticsearchClient client = new MarcElasticsearchClient();
    HttpEnreplacedy response = client.rootRequest();
    replacedertNull(response.getContentEncoding());
    replacedertEquals("content-type", response.getContentType().getName());
    replacedertEquals("application/json; charset=UTF-8", response.getContentType().getValue());
    String content = EnreplacedyUtils.toString(response);
    Object jsonObject = jsonProvider.parse(content);
    // JsonPath.fileToDict(jsonObject, jsonPath);
    // JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache(content);
    replacedertEquals("elasticsearch", JsonPath.read(jsonObject, "$.cluster_name"));
    replacedertEquals("hTkN47N", JsonPath.read(jsonObject, "$.name"));
    replacedertEquals("1gxeFwIRR5-tkEXwa2wVIw", JsonPath.read(jsonObject, "$.cluster_uuid"));
    replacedertEquals("You Know, for Search", JsonPath.read(jsonObject, "$.tagline"));
    replacedertEquals("5.5.1", JsonPath.read(jsonObject, "$.version.number"));
    replacedertEquals("6.6.0", JsonPath.read(jsonObject, "$.version.lucene_version"));
    replacedertEquals(2, client.getNumberOfTweets());
}

19 Source : AsynchronousSearchRestTestCase.java
with Apache License 2.0
from opendistro-for-elasticsearch

protected final <Resp> Resp parseEnreplacedy(final HttpEnreplacedy enreplacedy, final CheckedFunction<XContentParser, Resp, IOException> enreplacedyParser) throws IOException {
    if (enreplacedy == null) {
        throw new IllegalStateException("Response body expected but not returned");
    }
    if (enreplacedy.getContentType() == null) {
        throw new IllegalStateException("Elasticsearch didn't return the [Content-Type] header, unable to parse response body");
    }
    XContentType xContentType = XContentType.fromMediaTypeOrFormat(enreplacedy.getContentType().getValue());
    if (xContentType == null) {
        throw new IllegalStateException("Unsupported Content-Type: " + enreplacedy.getContentType().getValue());
    }
    try (XContentParser parser = xContentType.xContent().createParser(registry, DeprecationHandler.IGNORE_DEPRECATIONS, enreplacedy.getContent())) {
        return enreplacedyParser.apply(parser);
    }
}

19 Source : PutRequest.java
with Apache License 2.0
from OpenAPITools

@Override
public String getBodyContentType() {
    if (enreplacedy == null) {
        return null;
    }
    return enreplacedy.getContentType().getValue();
}

19 Source : LocalHttpClient.java
with Apache License 2.0
from luotuo

/**
 * 日志记录
 * @param request request
 * @return log request id
 */
private static String loggerRequest(HttpUriRequest request) {
    String id = UUID.randomUUID().toString();
    if (logger.isInfoEnabled() || logger.isDebugEnabled()) {
        if (request instanceof HttpEnreplacedyEnclosingRequestBase) {
            HttpEnreplacedyEnclosingRequestBase request_base = (HttpEnreplacedyEnclosingRequestBase) request;
            HttpEnreplacedy enreplacedy = request_base.getEnreplacedy();
            String content = null;
            // MULTIPART_FORM_DATA 请求类型判断
            if (enreplacedy.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1) {
                try {
                    content = EnreplacedyUtils.toString(enreplacedy);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            }
            logger.info("URI[{}] {} {} ContentLength:{} Content:{}", id, request.getURI().toString(), enreplacedy.getContentType(), enreplacedy.getContentLength(), content == null ? "multipart_form_data" : content);
        } else {
            logger.info("URI[{}] {}", id, request.getURI().toString());
        }
    }
    return id;
}

19 Source : KsqlVersionCheckerResponseHandlerTest.java
with Apache License 2.0
from kaiwaehner

@Test
public void testHandle() throws IOException {
    HttpResponse response = mock(HttpResponse.clreplaced);
    StatusLine statusLine = mock(StatusLine.clreplaced);
    HttpEnreplacedy enreplacedy = mock(HttpEnreplacedy.clreplaced);
    Logger log = mock(Logger.clreplaced);
    Header header = mock(Header.clreplaced);
    expect(response.getStatusLine()).andReturn(statusLine).once();
    expect(statusLine.getStatusCode()).andReturn(HttpStatus.SC_OK).once();
    expect(response.getEnreplacedy()).andReturn(enreplacedy).times(2);
    final ByteArrayInputStream bais = new ByteArrayInputStream("yolo".getBytes());
    expect(enreplacedy.getContent()).andReturn(bais).times(2);
    expect(enreplacedy.getContentType()).andReturn(header).times(1);
    expect(header.getElements()).andReturn(new HeaderElement[] {});
    expect(enreplacedy.getContentLength()).andReturn(4L).times(2);
    log.warn("yolo");
    expectLastCall().once();
    replay(response, statusLine, enreplacedy, header, log);
    KsqlVersionCheckerResponseHandler kvcr = new KsqlVersionCheckerResponseHandler(log);
    kvcr.handle(response);
    verify(response, statusLine, enreplacedy, header, log);
}

19 Source : ClientRequest.java
with MIT License
from josueeduardo

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {
    if (defaultHeaders != null) {
        for (Map.Entry<String, Object> entry : defaultHeaders.entrySet()) {
            // Do not set content-type for multipart and urlencoded
            if (!entry.getKey().equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || request.getBody() == null || !request.getBody().implicitContentType()) {
                request.header(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
    }
    if (!request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) {
        request.header(HttpHeaders.USER_AGENT, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(HttpHeaders.ACCEPT_ENCODING)) {
        request.header(HttpHeaders.ACCEPT_ENCODING, Constants.GZIP);
    }
    String urlToRequest;
    try {
        URL reqUrl = new URL(request.getUrl());
        URI uri = new URI(reqUrl.getProtocol(), reqUrl.getUserInfo(), reqUrl.getHost(), reqUrl.getPort(), URLDecoder.decode(reqUrl.getPath(), Constants.UTF_8), "", reqUrl.getRef());
        urlToRequest = uri.toURL().toString();
        if (reqUrl.getQuery() != null && !reqUrl.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals(Constants.QUESTION_MARK)) {
                urlToRequest += Constants.QUESTION_MARK;
            }
            urlToRequest += reqUrl.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals(Constants.QUESTION_MARK)) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RestClientException(e);
    }
    HttpRequestBase reqObj = null;
    switch(request.getHttpMethod()) {
        case GET:
            reqObj = new HttpGet(urlToRequest);
            break;
        case POST:
            reqObj = new HttpPost(urlToRequest);
            break;
        case PUT:
            reqObj = new HttpPut(urlToRequest);
            break;
        case DELETE:
            reqObj = new HttpDeleteWithBody(urlToRequest);
            break;
        case PATCH:
            reqObj = new HttpPatchWithBody(urlToRequest);
            break;
        case OPTIONS:
            reqObj = new HttpOptionsWithBody(urlToRequest);
            break;
        case HEAD:
            reqObj = new HttpHead(urlToRequest);
            break;
        default:
            throw new IllegalArgumentException("Invalid HTTP method: " + request.getHttpMethod());
    }
    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }
    // Set body
    if (request.getHttpMethod() != HttpMethod.GET && request.getHttpMethod() != HttpMethod.HEAD) {
        if (request.getBody() != null) {
            HttpEnreplacedy enreplacedy = request.getBody().getEnreplacedy();
            if (async) {
                if (reqObj.getHeaders(HttpHeaders.CONTENT_TYPE) == null || reqObj.getHeaders(HttpHeaders.CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(enreplacedy.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    enreplacedy.writeTo(output);
                    NByteArrayEnreplacedy en = new NByteArrayEnreplacedy(output.toByteArray());
                    ((HttpEnreplacedyEnclosingRequestBase) reqObj).setEnreplacedy(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEnreplacedyEnclosingRequestBase) reqObj).setEnreplacedy(enreplacedy);
            }
        }
    }
    return reqObj;
}

19 Source : HttpclientEntity.java
with MIT License
from dromara

@Override
public Header getContentType() {
    return enreplacedy.getContentType();
}

19 Source : HttpclientLogBodyMessage.java
with MIT License
from dromara

@Override
public String getBodyString() {
    if (enreplacedy == null) {
        return null;
    }
    if (enreplacedy.getContentType().getValue().startsWith("multipart/")) {
        Clreplaced[] paramTypes = new Clreplaced[0];
        Object[] args = new Object[0];
        List<FormBodyPart> parts = null;
        try {
            Method getMultipartMethod = enreplacedy.getClreplaced().getDeclaredMethod("getMultipart", paramTypes);
            getMultipartMethod.setAccessible(true);
            Object multipart = getMultipartMethod.invoke(enreplacedy, args);
            if (multipart != null) {
                Method getBodyPartsMethod = multipart.getClreplaced().getDeclaredMethod("getBodyParts", paramTypes);
                getBodyPartsMethod.setAccessible(true);
                parts = (List<FormBodyPart>) getBodyPartsMethod.invoke(multipart, args);
            }
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }
        Long contentLength = null;
        try {
            contentLength = enreplacedy.getContentLength();
        } catch (Throwable th) {
        }
        if (parts == null) {
            String result = "[" + enreplacedy.getContentType().getValue();
            if (contentLength != null) {
                result += "; length=" + contentLength;
            }
            return result + "]";
        } else {
            StringBuilder builder = new StringBuilder();
            builder.append("[").append(enreplacedy.getContentType().getValue());
            if (contentLength != null) {
                builder.append("; length=").append(contentLength);
            }
            builder.append("] parts:");
            for (FormBodyPart part : parts) {
                ContentBody partBody = part.getBody();
                MinimalField disposition = part.getHeader().getField("Content-Disposition");
                builder.append("\n             -- [").append(disposition.getBody());
                if (partBody instanceof StringBody) {
                    Reader reader = ((StringBody) partBody).getReader();
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    String value = null;
                    try {
                        value = getLogContentFormBufferedReader(bufferedReader);
                    } catch (IOException e) {
                    }
                    builder.append("; content-type=\"").append(((StringBody) partBody).getContentType()).append("\"");
                    builder.append("; value=\"").append(value).append("\"]");
                } else {
                    Long length = null;
                    length = partBody.getContentLength();
                    if (length != null) {
                        builder.append("; length=").append(length);
                    }
                    if (partBody instanceof HttpclientMultipartFileBody) {
                        builder.append("; content-type=\"").append(((HttpclientMultipartFileBody) partBody).getContentType()).append("\"");
                    }
                    builder.append("]");
                }
            }
            return builder.toString();
        }
    }
    return getLogContentForStringBody(enreplacedy);
}

19 Source : Page.java
with Apache License 2.0
from doubleview

/**
 * load the content of this page from a fetched HttpEnreplacedy.
 * @param enreplacedy HttpEnreplacedy
 * @param maxBytes The maximum number of bytes to read
 * @throws Exception when load fails
 */
public void load(HttpEnreplacedy enreplacedy, int maxBytes) throws Exception {
    contentType = null;
    Header type = enreplacedy.getContentType();
    if (type != null) {
        contentType = type.getValue();
    }
    contentEncoding = null;
    Header encoding = enreplacedy.getContentEncoding();
    if (encoding != null) {
        contentEncoding = encoding.getValue();
    }
    Charset charset = ContentType.getOrDefault(enreplacedy).getCharset();
    if (charset != null) {
        contentCharset = charset.displayName();
    } else {
        contentCharset = Charset.defaultCharset().displayName();
    }
    contentData = toByteArray(enreplacedy, maxBytes);
}

19 Source : ToOkhttp3Converter.java
with MIT License
from dkorobtsov

private static HttpEnreplacedy recreateHttpEnreplacedyFromString(String httpEnreplacedyContent, HttpEnreplacedy enreplacedy) {
    final Header contentType = enreplacedy.getContentType();
    final String contentTypeString = contentType == null ? "Content-Type=" + APPLICATION_JSON : String.format("%s=%s", contentType.getName(), contentType.getValue());
    final Header contentEncodingHeader = enreplacedy.getContentEncoding();
    final EnreplacedyBuilder enreplacedyBuilder = EnreplacedyBuilder.create().setContentType(ContentType.parse(contentTypeString)).setStream(new ByteArrayInputStream(httpEnreplacedyContent.getBytes()));
    if (contentEncodingHeader != null) {
        return enreplacedyBuilder.setContentEncoding(String.format("%s/%s", contentEncodingHeader.getName(), contentEncodingHeader.getValue())).build();
    }
    return enreplacedyBuilder.build();
}

19 Source : GoogleApacheHttpResponse.java
with Apache License 2.0
from devgianlu

@Override
public String getContentType() {
    HttpEnreplacedy enreplacedy = response.getEnreplacedy();
    if (enreplacedy != null) {
        Header contentTypeHeader = enreplacedy.getContentType();
        if (contentTypeHeader != null) {
            return contentTypeHeader.getValue();
        }
    }
    return null;
}

19 Source : CardcastService.java
with Apache License 2.0
from devgianlu

@Nullable
private String getUrlContent(String urlStr) throws IOException {
    HttpResponse resp = client.execute(new HttpGet(urlStr));
    StatusLine sl = resp.getStatusLine();
    if (sl.getStatusCode() != HttpStatus.SC_OK) {
        LOG.error(String.format("Got HTTP response code %s from Cardcast for %s", sl, urlStr));
        return null;
    }
    HttpEnreplacedy enreplacedy = resp.getEnreplacedy();
    String contentType = enreplacedy.getContentType().getValue();
    if (!Objects.equals(contentType, "application/json")) {
        LOG.error(String.format("Got content-type %s from Cardcast for %s", contentType, urlStr));
        return null;
    }
    return EnreplacedyUtils.toString(enreplacedy);
}

19 Source : ZhongHeHttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGet(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGet(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        httpGet.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpGet.addHeader("Accept-Language", "zh-EN,zh;q=0.9,en;q=0.8,la;q=0.7");
        httpGet.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        httpGet.addHeader("X-Requested-With", " XMLHttpRequest");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

public static Map<String, Object> doGetWithNoHeader(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        // httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        // httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        // httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7");
        // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        // httpGet.addHeader("X-Requested-With", " XMLHttpRequest");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGet(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new DefaultHttpClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGet(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        httpGet.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpGet.addHeader("Accept-Language", "zh-EN,zh;q=0.9,en;q=0.8,la;q=0.7");
        httpGet.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        httpGet.addHeader("X-Requested-With", " XMLHttpRequest");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        int status = response.getStatusLine().getStatusCode();
        resMap.put(HttpKey.STATUS_CODE, status);
        if (status == 302 || status == 301) {
            Header realUrl = response.getFirstHeader("location");
            resMap.put(HttpKey.REAL_URL, realUrl.getValue());
        }
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

public static Map<String, Object> doGetWithNoHeader(String url, String cookie, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        // httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        // httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        // httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7");
        // httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        // httpGet.addHeader("X-Requested-With", " XMLHttpRequest");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        int status = response.getStatusLine().getStatusCode();
        resMap.put(HttpKey.STATUS_CODE, status);
        if (status == 302 || status == 301) {
            Header realUrl = response.getFirstHeader("location");
            resMap.put(HttpKey.REAL_URL, realUrl.getValue());
        }
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGetWithHeader(String url, String cookie, Map<String, String> headers, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        httpGet.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpGet.addHeader("Accept-Language", "zh-EN,zh;q=0.9,en;q=0.8,la;q=0.7");
        httpGet.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        httpGet.addHeader("X-Requested-With", " XMLHttpRequest");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        if (!CollectionUtils.isEmpty(headers)) {
            for (Map.Entry entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        int status = response.getStatusLine().getStatusCode();
        resMap.put(HttpKey.STATUS_CODE, status);
        if (status == 302 || status == 301) {
            Header realUrl = response.getFirstHeader("location");
            resMap.put(HttpKey.REAL_URL, realUrl.getValue());
        }
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGet(String url, Map<String, String> headerMap, String cookie, String charset, String queryStr, String referer) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new DefaultHttpClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(referer)) {
            httpGet.addHeader("Referer", referer);
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (Map.Entry entry : headerMap.entrySet()) {
                httpGet.addHeader(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送get请求
 *
 * @param url     链接地址
 * @param charset 字符编码,若为null则默认utf-8
 * @return
 */
public static Map<String, Object> doGetWithHeader(String url, String cookie, Map<String, String> headers, String charset, String queryStr) {
    Map<String, Object> resMap = new HashMap<>();
    if (org.apache.commons.lang.StringUtils.isEmpty(charset)) {
        charset = "utf-8";
    }
    HttpClient httpClient = null;
    HttpGet httpGet = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(url + "?" + queryStr);
        }
        httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7");
        httpGet.addHeader("Connection", "keep-alive");
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpGet.addHeader("Cookie", cookie);
        }
        if (!CollectionUtils.isEmpty(headers)) {
            for (Map.Entry entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        HttpResponse response = httpClient.execute(httpGet);
        resMap.put(HttpKey.HEADERS, response.getAllHeaders());
        resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
        if (!ObjectUtils.isEmpty(response)) {
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpGet)) {
            httpGet.releaseConnection();
        }
    }
    return resMap;
}

19 Source : AwsProxyHttpServletRequestFormTest.java
with Apache License 2.0
from awslabs

@Test
public void postForm_getParts_parsing() {
    try {
        AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/form", "POST").header(MULTIPART_FORM_DATA.getContentType().getName(), MULTIPART_FORM_DATA.getContentType().getValue()).body(IOUtils.toString(MULTIPART_FORM_DATA.getContent())).build();
        HttpServletRequest request = new AwsProxyHttpServletRequest(proxyRequest, null, null);
        replacedertNotNull(request.getParts());
        replacedertEquals(2, request.getParts().size());
        replacedertEquals(PART_VALUE_1, IOUtils.toString(request.getPart(PART_KEY_1).getInputStream()));
        replacedertEquals(PART_VALUE_2, IOUtils.toString(request.getPart(PART_KEY_2).getInputStream()));
    } catch (IOException | ServletException e) {
        fail(e.getMessage());
    }
}

19 Source : AwsProxyHttpServletRequestFormTest.java
with Apache License 2.0
from awslabs

@Test
public void multipart_getParts_binary() {
    try {
        AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/form", "POST").header(MULTIPART_BINARY_DATA.getContentType().getName(), MULTIPART_BINARY_DATA.getContentType().getValue()).header(HttpHeaders.CONTENT_LENGTH, MULTIPART_BINARY_DATA.getContentLength() + "").binaryBody(MULTIPART_BINARY_DATA.getContent()).build();
        HttpServletRequest request = new AwsProxyHttpServletRequest(proxyRequest, null, null);
        replacedertNotNull(request.getParts());
        replacedertEquals(3, request.getParts().size());
        replacedertNotNull(request.getPart(FILE_KEY));
        replacedertEquals(FILE_SIZE, request.getPart(FILE_KEY).getSize());
        replacedertEquals(FILE_KEY, request.getPart(FILE_KEY).getName());
        replacedertEquals(FILE_NAME, request.getPart(FILE_KEY).getSubmittedFileName());
        replacedertEquals(PART_VALUE_1, IOUtils.toString(request.getPart(PART_KEY_1).getInputStream()));
        replacedertEquals(PART_VALUE_2, IOUtils.toString(request.getPart(PART_KEY_2).getInputStream()));
    } catch (IOException | ServletException e) {
        fail(e.getMessage());
    }
}

19 Source : HttpSolrCall.java
with Apache License 2.0
from apache

// TODO using Http2Client
private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException {
    HttpRequestBase method;
    HttpEnreplacedy httpEnreplacedy = null;
    ModifiableSolrParams updatedQueryParams = new ModifiableSolrParams(queryParams);
    int forwardCount = queryParams.getInt(INTERNAL_REQUEST_COUNT, 0) + 1;
    updatedQueryParams.set(INTERNAL_REQUEST_COUNT, forwardCount);
    String queryStr = updatedQueryParams.toQueryString();
    try {
        String urlstr = coreUrl + queryStr;
        boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod());
        if ("GET".equals(req.getMethod())) {
            method = new HttpGet(urlstr);
        } else if ("HEAD".equals(req.getMethod())) {
            method = new HttpHead(urlstr);
        } else if (isPostOrPutRequest) {
            HttpEnreplacedyEnclosingRequestBase enreplacedyRequest = "POST".equals(req.getMethod()) ? new HttpPost(urlstr) : new HttpPut(urlstr);
            InputStream in = req.getInputStream();
            HttpEnreplacedy enreplacedy = new InputStreamEnreplacedy(in, req.getContentLength());
            enreplacedyRequest.setEnreplacedy(enreplacedy);
            method = enreplacedyRequest;
        } else if ("DELETE".equals(req.getMethod())) {
            method = new HttpDelete(urlstr);
        } else if ("OPTIONS".equals(req.getMethod())) {
            method = new HttpOptions(urlstr);
        } else {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unexpected method type: " + req.getMethod());
        }
        for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
            String headerName = e.nextElement();
            if (!"host".equalsIgnoreCase(headerName) && !"authorization".equalsIgnoreCase(headerName) && !"accept".equalsIgnoreCase(headerName)) {
                method.addHeader(headerName, req.getHeader(headerName));
            }
        }
        // These headers not supported for HttpEnreplacedyEnclosingRequests
        if (method instanceof HttpEnreplacedyEnclosingRequest) {
            method.removeHeaders(TRANSFER_ENCODING_HEADER);
            method.removeHeaders(CONTENT_LENGTH_HEADER);
        }
        final HttpResponse response = solrDispatchFilter.httpClient.execute(method, HttpClientUtil.createNewHttpClientRequestContext());
        int httpStatus = response.getStatusLine().getStatusCode();
        httpEnreplacedy = response.getEnreplacedy();
        resp.setStatus(httpStatus);
        for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext(); ) {
            Header header = responseHeaders.nextHeader();
            // We pull out these two headers below because they can cause chunked
            // encoding issues with Tomcat
            if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER) && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) {
                // NOTE: explicitly using 'setHeader' instead of 'addHeader' so that
                // the remote nodes values for any response headers will overide any that
                // may have already been set locally (ex: by the local jetty's RewriteHandler config)
                resp.setHeader(header.getName(), header.getValue());
            }
        }
        if (httpEnreplacedy != null) {
            if (httpEnreplacedy.getContentEncoding() != null)
                resp.setHeader(httpEnreplacedy.getContentEncoding().getName(), httpEnreplacedy.getContentEncoding().getValue());
            if (httpEnreplacedy.getContentType() != null)
                resp.setContentType(httpEnreplacedy.getContentType().getValue());
            InputStream is = httpEnreplacedy.getContent();
            OutputStream os = resp.getOutputStream();
            IOUtils.copyLarge(is, os);
        }
    } catch (IOException e) {
        sendError(new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error trying to proxy request for url: " + coreUrl + " with _forwardCount: " + forwardCount, e));
    } finally {
        Utils.consumeFully(httpEnreplacedy);
    }
}

18 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);
    }
}

18 Source : TestFormBuilder.java
with BSD 3-Clause "New" or "Revised" License
from Unidata

@Test
public void testSimple() throws Exception {
    HTTPSession.resetInterceptors();
    try {
        HTTPFormBuilder builder = buildForm(false);
        HttpEnreplacedy content = builder.build();
        try (HTTPMethod postMethod = HTTPFactory.Post(NULLURL)) {
            postMethod.setRequestContent(content);
            // Execute, but ignore any problems
            try {
                postMethod.execute();
            } catch (Exception e) {
            // ignore
            }
        }
        // Get the request that was used
        HTTPUtil.InterceptRequest dbgreq = HTTPSession.debugRequestInterceptor();
        replacedert.replacedertTrue("Could not get debug request", dbgreq != null);
        HttpEnreplacedy enreplacedy = dbgreq.getRequestEnreplacedy();
        replacedert.replacedertTrue("Could not get debug enreplacedy", enreplacedy != null);
        // Extract the form info
        Header ct = enreplacedy.getContentType();
        String body = extract(enreplacedy, ct, false);
        replacedert.replacedertTrue("Malformed debug request", body != null);
        if (DEBUG || prop_visual)
            visual("TestFormBuilder.testsimple.RAW", body);
        body = genericize(body, OSTEXT, null, null);
        if (DEBUG)
            visual("TestFormBuilder.testsimple.LOCALIZED", body);
        String diffs = UnitTestCommon.compare("TestFormBuilder.testSimpl", simplebaseline, body);
        if (diffs != null) {
            System.err.println("TestFormBuilder.testsimple.diffs:\n" + diffs);
            replacedert.replacedertTrue("TestFormBuilder.testSimple: ***FAIL", false);
        }
    } catch (Exception e) {
        replacedert.replacedertTrue("***FAIL: " + e.getCause(), false);
        if (DEBUG)
            e.printStackTrace();
    }
}

18 Source : TestFormBuilder.java
with BSD 3-Clause "New" or "Revised" License
from Unidata

@Test
public void testMultiPart() throws Exception {
    // Try to create a tmp file
    attach3file = HTTPUtil.fillTempFile("attach3.txt", ATTACHTEXT);
    attach3file.deleteOnExit();
    HTTPSession.resetInterceptors();
    try {
        HTTPFormBuilder builder = buildForm(true);
        HttpEnreplacedy content = builder.build();
        try (HTTPMethod postMethod = HTTPFactory.Post(NULLURL)) {
            postMethod.setRequestContent(content);
            // Execute, but ignore any problems
            try {
                postMethod.execute();
            } catch (Exception e) {
            // ignore
            }
        }
        // Get the request that was used
        HTTPUtil.InterceptRequest dbgreq = HTTPSession.debugRequestInterceptor();
        replacedert.replacedertTrue("Could not get debug request", dbgreq != null);
        HttpEnreplacedy enreplacedy = dbgreq.getRequestEnreplacedy();
        replacedert.replacedertTrue("Could not get debug enreplacedy", enreplacedy != null);
        // Extract the form info
        Header ct = enreplacedy.getContentType();
        String body = extract(enreplacedy, ct, true);
        replacedert.replacedertTrue("Malformed debug request", body != null);
        if (DEBUG || prop_visual)
            visual("TestFormBuilder.testmultipart.RAW", body);
        // Get the contenttype boundary
        String boundary = getboundary(ct);
        replacedert.replacedertTrue("Missing boundary info", boundary != null);
        String attach3 = getattach(body, "attach3");
        replacedert.replacedertTrue("Missing attach3 info", attach3 != null);
        body = genericize(body, OSTEXT, boundary, attach3);
        if (DEBUG)
            visual("TestFormBuilder.testmultipart.LOCALIZED", body);
        String diffs = UnitTestCommon.compare("TestFormBuilder.testMultiPart", multipartbaseline, body);
        if (diffs != null) {
            System.err.println("TestFormBuilder.testmultipart.diffs:\n" + diffs);
            replacedert.replacedertTrue("TestFormBuilder.testmultipart: ***FAIL", false);
        }
    } catch (Exception e) {
        replacedert.replacedertTrue("***FAIL: " + e.getCause(), false);
        if (DEBUG)
            e.printStackTrace();
    }
}

18 Source : ConanClient.java
with Eclipse Public License 1.0
from sonatype-nexus-community

public HttpResponse getHttpResponse(final String path) throws IOException {
    try (CloseableHttpResponse closeableHttpResponse = super.get(path)) {
        HttpEnreplacedy enreplacedy = closeableHttpResponse.getEnreplacedy();
        BasicHttpEnreplacedy basicHttpEnreplacedy = new BasicHttpEnreplacedy();
        String content = EnreplacedyUtils.toString(enreplacedy);
        basicHttpEnreplacedy.setContent(IOUtils.toInputStream(content));
        basicHttpEnreplacedy.setContentEncoding(enreplacedy.getContentEncoding());
        basicHttpEnreplacedy.setContentLength(enreplacedy.getContentLength());
        basicHttpEnreplacedy.setContentType(enreplacedy.getContentType());
        basicHttpEnreplacedy.setChunked(enreplacedy.isChunked());
        StatusLine statusLine = closeableHttpResponse.getStatusLine();
        HttpResponse response = new BasicHttpResponse(statusLine);
        response.setEnreplacedy(basicHttpEnreplacedy);
        response.setHeaders(closeableHttpResponse.getAllHeaders());
        response.setLocale(closeableHttpResponse.getLocale());
        return response;
    }
}

18 Source : UploadHelper.java
with Apache License 2.0
from SAP

public static void simulateFileUpload(HttpServletRequestMock requestMock, String fileName, String mimeType) throws IOException {
    MultipartEnreplacedyBuilder builder = MultipartEnreplacedyBuilder.create();
    builder = builder.addBinaryBody(fileName, IOUtils.resourceToByteArray("/" + fileName), ContentType.create(mimeType), fileName);
    HttpEnreplacedy enreplacedy = builder.build();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    enreplacedy.writeTo(bos);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    when(requestMock.getMethod()).thenReturn("POST");
    when(requestMock.getContentType()).thenReturn(enreplacedy.getContentType().getValue());
    when(requestMock.getContentLength()).thenReturn((int) enreplacedy.getContentLength());
    when(requestMock.getInputStream()).thenReturn(new MockServletInputStream(bis));
}

18 Source : RemoteDicMonitor.java
with Apache License 2.0
from PeterMen

/**
 * 从远程服务器上下载自定义词条
 */
public static List<String> getRemoteWordsUnprivileged(String location) {
    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String charset = "UTF-8";
            // 获取编码,默认为utf-8
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            if (enreplacedy != null) {
                Header contentType = enreplacedy.getContentType();
                if (contentType != null && contentType.getValue() != null) {
                    String typeValue = contentType.getValue();
                    if (typeValue != null && typeValue.contains("charset=")) {
                        charset = typeValue.substring(typeValue.lastIndexOf("=") + 1);
                    }
                }
                if (enreplacedy.getContentLength() > 0) {
                    in = new BufferedReader(new InputStreamReader(enreplacedy.getContent(), charset));
                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.add(line);
                    }
                    in.close();
                    response.close();
                    return buffer;
                }
            }
        }
        response.close();
    } catch (IllegalStateException | IOException e) {
        logger.error("getRemoteWords {} error", e, location);
    }
    return buffer;
}

18 Source : AbstractJAXRSTestCase.java
with Apache License 2.0
from osgi

protected String replacedertResponse(CloseableHttpResponse response, int responseCode, String mediaType) throws IOException {
    replacedertEquals(responseCode, response.getStatusLine().getStatusCode());
    HttpEnreplacedy enreplacedy = response.getEnreplacedy();
    if (mediaType != null) {
        replacedertEquals(mediaType, enreplacedy.getContentType().getValue());
    }
    if (enreplacedy != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        enreplacedy.writeTo(baos);
        return baos.toString("UTF-8");
    }
    return null;
}

18 Source : MockCloseableHttpResponseBuilder.java
with Apache License 2.0
from opendistro-for-elasticsearch

public CloseableHttpResponse build() throws IOException {
    StatusLine mockStatusLine = mock(StatusLine.clreplaced);
    HttpEnreplacedy mockEnreplacedy = mock(HttpEnreplacedy.clreplaced);
    CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.clreplaced);
    when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
    when(mockStatusLine.getStatusCode()).thenReturn(httpCode);
    when(mockResponse.getEnreplacedy()).thenReturn(mockEnreplacedy);
    when(mockEnreplacedy.getContentType()).thenReturn(contentTypeHeader);
    // this mimics a real stream that can be consumed just once
    // as is the case with a server response. This makes this mock
    // response object single-use with regards to reading the
    // response content.
    when(mockEnreplacedy.getContent()).thenReturn(responseBody == null ? null : new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
    return mockResponse;
}

18 Source : DownloadJob.java
with Apache License 2.0
from openaudible

public void download() throws IOException {
    String cust_id = b.get(BookElement.cust_id);
    String user_id = b.get(BookElement.user_id);
    String awtype = "AAX";
    String codec = b.getCodec();
    if (codec.isEmpty())
        codec = "LC_64_22050_stereo";
    /*
           http://cds.audible.com/download?
                user_id=xxx[about 60 chars] &
                product_id=BK_RAND_003188&
                codec=LC_32_22050_Mono&
                awtype=AAX&
                cust_id= [ same as user-id currently? ]
        */
    String url = "http://cds.audible.com/download";
    // crypt
    url += "?user_id=" + user_id;
    // BK_ABCD_123456
    url += "&product_id=" + b.getProduct_id();
    // LC_32_22050_Mono
    url += "&codec=" + codec;
    // AAX
    url += "&awtype=" + awtype;
    url += "&cust_id=" + cust_id;
    LOG.info("Download book: " + b + " url=" + url);
    File tmp = null;
    long start = System.currentTimeMillis();
    FileOutputStream fos = null;
    boolean success = false;
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader("User-Agent", "Audible ADM 6.6.0.19;Windows Vista  Build 9200");
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(30000).build();
        bld.setDefaultRequestConfig(defaultRequestConfig);
        httpclient = bld.build();
        response = httpclient.execute(httpGet);
        int code = response.getStatusLine().getStatusCode();
        if (code != 200)
            throw new IOException(response.getStatusLine().toString());
        HttpEnreplacedy enreplacedy = response.getEnreplacedy();
        Header ctyp = enreplacedy.getContentType();
        if (ctyp != null) {
            if (!ctyp.getValue().contains("audio")) {
                String err = "Download error:";
                if (enreplacedy.getContentLength() < 256) {
                    err += EnreplacedyUtils.toString(enreplacedy);
                }
                err += " for " + b;
                // 
                throw new IOException(err);
            }
        }
        tmp = new File(Directories.getTmpDir(), destFile.getName() + ".part");
        if (tmp.exists()) {
            boolean v = tmp.delete();
            replacedert (v);
        }
        fos = new FileOutputStream(tmp);
        CopyWithProgress.copyWithProgress(getByteReporter(), 500, enreplacedy.getContent(), fos);
        // / IO.copy(enreplacedy.getContent(), fos);
        if (quit) {
            success = false;
            throw new IOException("quit");
        }
        success = true;
    } finally {
        response.close();
        if (fos != null)
            fos.close();
        if (httpclient != null)
            httpclient.close();
        if (success) {
            if (tmp != null) {
                boolean ok = tmp.renameTo(destFile);
                if (!ok)
                    throw new IOException("failed to rename." + tmp.getAbsolutePath() + " to " + destFile.getAbsolutePath());
            }
            long time = System.currentTimeMillis() - start;
            long bytes = destFile.length();
            double bps = bytes / (time / 1000.0);
            LOG.info("Downloaded " + destFile.getName() + " bytes=" + bytes + " time=" + time + " Kbps=" + (int) (bps / 1024.0));
        } else {
            if (tmp != null)
                tmp.delete();
            destFile.delete();
        }
    }
}

18 Source : ProxyResourceHandler.java
with Apache License 2.0
from Erudika

Response proxyRequest(String method, ContainerRequestContext ctx) {
    if (!Config.getConfigBoolean("es.proxy_enabled", false)) {
        return Response.status(Response.Status.FORBIDDEN.getStatusCode(), "This feature is disabled.").build();
    }
    String appid = ParaObjectUtils.getAppidFromAuthHeader(ctx.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
    if (StringUtils.isBlank(appid)) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    String path = getCleanPath(appid, getPath(ctx));
    try {
        if (path.endsWith("/reindex") && POST.equals(method)) {
            return handleReindexTask(appid, ctx.getUriInfo().getQueryParameters().getFirst("destinationIndex"));
        }
        Header[] headers = getHeaders(ctx.getHeaders());
        HttpEnreplacedy resp;
        RestClient client = getClient();
        if (client != null) {
            org.elasticsearch.client.Request esRequest = new Request(method, path);
            RequestOptions.Builder opts = RequestOptions.DEFAULT.toBuilder();
            for (Header header : headers) {
                opts.addHeader(header.getName(), header.getValue());
            }
            esRequest.setOptions(opts);
            if (ctx.getEnreplacedyStream() != null && ctx.getEnreplacedyStream().available() > 0) {
                HttpEnreplacedy body = new InputStreamEnreplacedy(ctx.getEnreplacedyStream(), ContentType.APPLICATION_JSON);
                esRequest.setEnreplacedy(body);
                resp = client.performRequest(esRequest).getEnreplacedy();
            } else {
                resp = client.performRequest(esRequest).getEnreplacedy();
            }
            if (resp != null && resp.getContent() != null) {
                Header type = resp.getContentType();
                Object response = getTransformedResponse(appid, resp.getContent(), ctx);
                return Response.ok(response).header(type.getName(), type.getValue()).build();
            }
        }
    } catch (Exception ex) {
        logger.warn("Failed to proxy '{} {}' to Elasticsearch: {}", method, path, ex.getMessage());
    }
    return Response.status(Response.Status.BAD_REQUEST).build();
}

18 Source : PushHandlerTest.java
with Apache License 2.0
from eiichiro

@Test
public void testHandleRequest() throws UnsupportedOperationException, IOException {
    // No 'jar' field - APIGatewayProxyResponseEvent with status code 400
    APIGatewayProxyRequestEvent input = new APIGatewayProxyRequestEvent();
    HttpEnreplacedy enreplacedy = MultipartEnreplacedyBuilder.create().addBinaryBody("not-jar", Paths.get(getClreplaced().getResource("/push-handler-test.jar").getPath()).toFile()).build();
    Map<String, String> headers = new HashMap<>();
    Header header = enreplacedy.getContentType();
    headers.put(header.getName(), header.getValue());
    // API Gateway automatically encodes raw binary bytes as Base64 string.
    input.setBody(Base64.getEncoder().encodeToString(IOUtils.toString(enreplacedy.getContent()).getBytes()));
    input.setHeaders(headers);
    PushHandler handler = new PushHandler();
    APIGatewayProxyResponseEvent output = handler.handleRequest(input, null);
    replacedertThat(output.getStatusCode(), is(400));
    replacedertThat(output.getBody(), is("Parameter 'jar' is required"));
    // Prodigy throws IllegalArgumentException - APIGatewayProxyResponseEvent with status code 400
    input = new APIGatewayProxyRequestEvent();
    enreplacedy = MultipartEnreplacedyBuilder.create().addBinaryBody("jar", Paths.get(getClreplaced().getResource("/push-handler-test.zip").getPath()).toFile()).build();
    headers = new HashMap<>();
    header = enreplacedy.getContentType();
    headers.put(header.getName(), header.getValue());
    input.setBody(Base64.getEncoder().encodeToString(IOUtils.toString(enreplacedy.getContent()).getBytes()));
    input.setHeaders(headers);
    handler = new PushHandler();
    output = handler.handleRequest(input, null);
    replacedertThat(output.getStatusCode(), is(400));
    replacedertThat(output.getBody(), is("Parameter 'name' must be *.jar"));
    // Prodigy throws Exception - APIGatewayProxyResponseEvent with status code 500
    input = new APIGatewayProxyRequestEvent();
    enreplacedy = MultipartEnreplacedyBuilder.create().addBinaryBody("jar", Paths.get(getClreplaced().getResource("/push-handler-test.jar").getPath()).toFile()).build();
    headers = new HashMap<>();
    header = enreplacedy.getContentType();
    headers.put(header.getName(), header.getValue());
    input.setBody(Base64.getEncoder().encodeToString(IOUtils.toString(enreplacedy.getContent()).getBytes()));
    input.setHeaders(headers);
    handler = new PushHandler();
    Repository repository = mock(Repository.clreplaced);
    doThrow(new IllegalStateException("hello")).when(repository).save(anyString(), ArgumentMatchers.any(InputStream.clreplaced));
    Prodigy.container(new Container(mock(Scheduler.clreplaced), repository));
    output = handler.handleRequest(input, null);
    replacedertThat(output.getStatusCode(), is(500));
    replacedertThat(output.getBody(), is("hello"));
    // Other - APIGatewayProxyResponseEvent with JSON object and status code 200
    input = new APIGatewayProxyRequestEvent();
    enreplacedy = MultipartEnreplacedyBuilder.create().addBinaryBody("jar", Paths.get(getClreplaced().getResource("/push-handler-test.jar").getPath()).toFile()).build();
    headers = new HashMap<>();
    header = enreplacedy.getContentType();
    headers.put(header.getName(), header.getValue());
    input.setBody(Base64.getEncoder().encodeToString(IOUtils.toString(enreplacedy.getContent()).getBytes()));
    input.setHeaders(headers);
    handler = new PushHandler();
    repository = mock(Repository.clreplaced);
    doNothing().when(repository).save(anyString(), ArgumentMatchers.any(InputStream.clreplaced));
    Prodigy.container(new Container(mock(Scheduler.clreplaced), repository));
    output = handler.handleRequest(input, null);
    replacedertThat(output.getStatusCode(), is(200));
    replacedertThat(output.getBody(), is("{}"));
}

18 Source : Dictionary.java
with Apache License 2.0
from crazyyanchao

/**
 * 从远程服务器上下载自定义词条
 */
private static List<String> getRemoteWordsUnprivileged(String location) {
    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String charset = "UTF-8";
            // 获取编码,默认为utf-8
            HttpEnreplacedy enreplacedy = response.getEnreplacedy();
            if (enreplacedy != null) {
                Header contentType = enreplacedy.getContentType();
                if (contentType != null && contentType.getValue() != null) {
                    String typeValue = contentType.getValue();
                    if (typeValue != null && typeValue.contains("charset=")) {
                        charset = typeValue.substring(typeValue.lastIndexOf("=") + 1);
                    }
                }
                if (enreplacedy.getContentLength() > 0) {
                    in = new BufferedReader(new InputStreamReader(enreplacedy.getContent(), charset));
                    String line;
                    while ((line = in.readLine()) != null) {
                        buffer.add(line);
                    }
                    in.close();
                    response.close();
                    return buffer;
                }
            }
        }
        response.close();
    } catch (IllegalStateException | IOException e) {
        logger.error("getRemoteWords " + location + " error", e);
    }
    return buffer;
}

18 Source : ZhongHeHttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送post请求组
 *
 * @param url
 * @param list
 * @param charset
 * @return
 */
public static Map<String, Object> doPost(String url, List<NameValuePair> list, String cookie, String charset, String referer, String queryStr) {
    if (StringUtils.isEmpty(charset)) {
        charset = "UTF-8";
    }
    Map<String, Object> resMap = new HashMap<>();
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpPost = new HttpPost(url);
        } else {
            httpPost = new HttpPost(url + "?" + queryStr);
        }
        // httpPost.addHeader("Accept","*/*");
        // httpPost.addHeader("Accept-Encoding","gzip, deflate, br");
        // httpPost.addHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7");
        // httpPost.addHeader("User-Agent"," Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        httpPost.addHeader("Cookie", cookie);
        if (!org.apache.commons.lang.StringUtils.isEmpty(referer)) {
            httpPost.addHeader("Referer", referer);
        }
        if (!CollectionUtils.isEmpty(list)) {
            UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(list, charset);
            httpPost.setEnreplacedy(enreplacedy);
        }
        HttpResponse response = httpClient.execute(httpPost);
        if (!ObjectUtils.isEmpty(response)) {
            Header[] headers = response.getAllHeaders();
            resMap.put(HttpKey.HEADERS, headers);
            resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpPost)) {
            httpPost.releaseConnection();
        }
    }
    return resMap;
}

18 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送post请求组
 *
 * @param url
 * @param list
 * @param charset
 * @return
 */
public static Map<String, Object> doPost(String url, List<NameValuePair> list, String cookie, String charset, String referer, String queryStr) {
    if (StringUtils.isEmpty(charset)) {
        charset = "UTF-8";
    }
    Map<String, Object> resMap = new HashMap<>();
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpPost = new HttpPost(url);
        } else {
            httpPost = new HttpPost(url + "?" + queryStr);
        }
        httpPost.addHeader("Accept", "*/*");
        httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,la;q=0.7");
        httpPost.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        httpPost.addHeader("Cookie", cookie);
        if (!org.apache.commons.lang.StringUtils.isEmpty(referer)) {
            httpPost.addHeader("Referer", referer);
        }
        if (!CollectionUtils.isEmpty(list)) {
            UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(list, charset);
            httpPost.setEnreplacedy(enreplacedy);
        }
        HttpResponse response = httpClient.execute(httpPost);
        if (!ObjectUtils.isEmpty(response)) {
            Header[] headers = response.getAllHeaders();
            resMap.put(HttpKey.HEADERS, headers);
            resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpPost)) {
            httpPost.releaseConnection();
        }
    }
    return resMap;
}

18 Source : HttpsClientUtils.java
with GNU General Public License v2.0
from CipherChina

public static Map<String, Object> doPostWithNoHeader(String url, List<NameValuePair> list, String cookie, String charset, String referer, String queryStr) {
    if (StringUtils.isEmpty(charset)) {
        charset = "UTF-8";
    }
    Map<String, Object> resMap = new HashMap<>();
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        httpClient = new SSLClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpPost = new HttpPost(url);
        } else {
            httpPost = new HttpPost(url + "?" + queryStr);
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(cookie)) {
            httpPost.addHeader("Cookie", cookie);
        }
        if (!org.apache.commons.lang.StringUtils.isEmpty(referer)) {
            httpPost.addHeader("Referer", referer);
        }
        if (!CollectionUtils.isEmpty(list)) {
            UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(list, charset);
            httpPost.setEnreplacedy(enreplacedy);
        }
        HttpResponse response = httpClient.execute(httpPost);
        if (!ObjectUtils.isEmpty(response)) {
            Header[] headers = response.getAllHeaders();
            resMap.put(HttpKey.HEADERS, headers);
            resMap.put(HttpKey.STATUS_CODE, response.getStatusLine().getStatusCode());
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpPost)) {
            httpPost.releaseConnection();
        }
    }
    return resMap;
}

18 Source : HttpClientUtils.java
with GNU General Public License v2.0
from CipherChina

/**
 * 发送post请求组
 *
 * @param url
 * @param list
 * @param charset
 * @return
 */
public static Map<String, Object> doPost(String url, List<NameValuePair> list, String cookie, String charset, String queryStr) {
    if (StringUtils.isEmpty(charset)) {
        charset = "UTF-8";
    }
    Map<String, Object> resMap = new HashMap<>();
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    try {
        httpClient = new DefaultHttpClient();
        if (StringUtils.isEmpty(queryStr)) {
            httpPost = new HttpPost(url);
        } else {
            httpPost = new HttpPost(url + "?" + queryStr);
        }
        httpPost.addHeader("Cookie", cookie);
        if (!CollectionUtils.isEmpty(list)) {
            UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(list, charset);
            httpPost.setEnreplacedy(enreplacedy);
        }
        HttpResponse response = httpClient.execute(httpPost);
        if (!ObjectUtils.isEmpty(response)) {
            Header[] headers = response.getAllHeaders();
            resMap.put(HttpKey.HEADERS, headers);
            int status = response.getStatusLine().getStatusCode();
            resMap.put(HttpKey.STATUS_CODE, status);
            if (status == 302 || status == 301) {
                Header realUrl = response.getFirstHeader("location");
                resMap.put(HttpKey.REAL_URL, realUrl.getValue());
            }
            HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
            if (!ObjectUtils.isEmpty(resEnreplacedy)) {
                if (resEnreplacedy.getContentType() != null) {
                    if (!StringUtils.isEmpty(resEnreplacedy.getContentType().getValue())) {
                        resMap.put(HttpKey.PAGETYPE, resEnreplacedy.getContentType().getValue());
                    }
                }
                result = EnreplacedyUtils.toString(resEnreplacedy, charset);
                resMap.put(HttpKey.RES, result);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!ObjectUtils.isEmpty(httpPost)) {
            httpPost.releaseConnection();
        }
    }
    return resMap;
}

See More Examples