Search in sources :

Example 1 with HttpReceive

use of pro.tools.http.pojo.HttpReceive in project protools by SeanDragon.

the class ToolHttp method sendHttp.

/**
 * 用于请求http
 *
 * @param send
 *         里面包含请求的信息
 *
 * @return 响应的信息
 */
public static HttpReceive sendHttp(HttpSend send, HttpBuilder httpBuilder) {
    HttpReceive httpReceive = new HttpReceive();
    httpReceive.setHaveError(true);
    String url = send.getUrl();
    URI uri;
    try {
        uri = new URL(url).toURI();
    } catch (MalformedURLException | URISyntaxException e) {
        httpReceive.setErrMsg("不是一个有效的URL").setThrowable(e);
        return httpReceive;
    }
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if (HttpScheme.HTTP.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (HttpScheme.HTTPS.equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    Map<String, Object> param = send.getParams();
    Map<String, Object> sendHeaders = send.getHeaders();
    HttpMethod method = send.getMethod();
    Charset charset = send.getCharset();
    AsyncHttpClient asyncHttpClient = httpBuilder.buildDefaultClient();
    RequestBuilder builder = new RequestBuilder(method.name());
    AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.prepareRequest(builder.build());
    // 设置编码
    requestBuilder.setBodyEncoding(charset.toString());
    if (param != null) {
        param.forEach((key, value) -> requestBuilder.addQueryParam(key, value.toString()));
    }
    // 设置基本请求头
    requestBuilder.addHeader(HttpHeaderNames.CONTENT_TYPE.toString(), HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED + ";charset" + charset.toString()).addHeader(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString()).addHeader(HttpHeaderNames.ACCEPT_ENCODING.toString(), HttpHeaderValues.GZIP_DEFLATE.toString()).addHeader(HttpHeaderNames.USER_AGENT.toString(), "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)").addHeader(HttpHeaderNames.CACHE_CONTROL.toString(), "max-age=0").addHeader(HttpHeaderNames.HOST.toString(), host + ":" + port).addHeader("DNT", "1");
    if (sendHeaders != null) {
        sendHeaders.forEach((key, value) -> requestBuilder.addHeader(key, value.toString()));
    }
    // TODO: 2017/7/27 Cookie未加入
    ListenableFuture<Response> future = requestBuilder.execute();
    try {
        Response response = future.get();
        Map<String, String> responseHeaderMap = Maps.newHashMap();
        if (send.getNeedReceiveHeaders()) {
            FluentCaseInsensitiveStringsMap responseHeaders = response.getHeaders();
            responseHeaders.forEach((k, v) -> {
                if (v.size() == 1) {
                    responseHeaderMap.put(k, v.get(0));
                } else {
                    responseHeaderMap.put(k, ToolJson.anyToJson(v));
                }
            });
        }
        int responseStatusCode = response.getStatusCode();
        if (responseStatusCode != 200) {
            throw new HttpException("本次请求响应码不是200,是" + responseStatusCode);
        }
        String responseBody = response.getResponseBody();
        if (log.isDebugEnabled()) {
            log.debug(responseBody);
        }
        httpReceive.setStatusCode(responseStatusCode).setStatusText(response.getStatusText()).setResponseBody(responseBody).setResponseHeader(responseHeaderMap).setHaveError(false);
    } catch (InterruptedException e) {
        httpReceive.setErrMsg("http组件出现问题!").setThrowable(e);
    } catch (IOException e) {
        httpReceive.setErrMsg("获取返回内容失败!").setThrowable(e);
    } catch (ExecutionException e) {
        httpReceive.setErrMsg("访问URL失败!").setThrowable(e);
    } catch (HttpException e) {
        httpReceive.setErrMsg(e.getMessage()).setThrowable(e);
    }
    if (httpReceive.getHaveError()) {
        if (log.isWarnEnabled()) {
            Throwable throwable = httpReceive.getThrowable();
            log.warn(ToolFormat.toException(throwable), throwable);
        }
    }
    httpReceive.setIsDone(true);
    return httpReceive;
}
Also used : HttpReceive(pro.tools.http.pojo.HttpReceive) MalformedURLException(java.net.MalformedURLException) RequestBuilder(com.ning.http.client.RequestBuilder) Charset(java.nio.charset.Charset) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) URL(java.net.URL) Response(com.ning.http.client.Response) FluentCaseInsensitiveStringsMap(com.ning.http.client.FluentCaseInsensitiveStringsMap) HttpException(pro.tools.http.pojo.HttpException) ExecutionException(java.util.concurrent.ExecutionException) HttpMethod(pro.tools.http.pojo.HttpMethod) AsyncHttpClient(com.ning.http.client.AsyncHttpClient)

Example 2 with HttpReceive

use of pro.tools.http.pojo.HttpReceive in project protools by SeanDragon.

the class ToolSendHttp method send.

public static HttpReceive send(HttpSend httpSend, OkHttpClient okHttpClient) {
    final HttpReceive httpReceive = new HttpReceive();
    httpReceive.setHaveError(true);
    try {
        Request request = convertRequest(httpSend);
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        ResponseBody body = response.body();
        if (body == null) {
            throw new HttpException("发送http失败,响应体为空");
        }
        final Map<String, String> responseHeaders = Maps.newHashMap();
        if (httpSend.getNeedReceiveHeaders()) {
            final Headers headers = response.headers();
            final Set<String> headerNameSet = headers.names();
            headerNameSet.forEach(oneHeaderName -> {
                final String oneHeaderValue = headers.get(oneHeaderName);
                responseHeaders.put(oneHeaderName, oneHeaderValue);
            });
        }
        int responseStatusCode = response.code();
        if (responseStatusCode != 200) {
            throw new HttpException("本次请求响应码不是200,是" + responseStatusCode);
        }
        String responseBody = body.string();
        if (log.isDebugEnabled()) {
            log.debug(responseBody);
        }
        httpReceive.setResponseBody(responseBody).setHaveError(false).setStatusCode(responseStatusCode).setStatusText(responseStatusCode + "").setResponseHeader(responseHeaders);
        response.close();
        okHttpClient.dispatcher().executorService().shutdown();
    } catch (IOException e) {
        httpReceive.setErrMsg("获取返回内容失败!").setThrowable(e);
    } catch (HttpException e) {
        httpReceive.setErrMsg(e.getMessage()).setThrowable(e);
    }
    if (httpReceive.getHaveError()) {
        if (log.isWarnEnabled()) {
            Throwable throwable = httpReceive.getThrowable();
            log.warn(ToolFormat.toException(throwable), throwable);
        }
    }
    httpReceive.setIsDone(true);
    return httpReceive;
}
Also used : HttpReceive(pro.tools.http.pojo.HttpReceive) Call(okhttp3.Call) Headers(okhttp3.Headers) Request(okhttp3.Request) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) HttpException(pro.tools.http.pojo.HttpException)

Example 3 with HttpReceive

use of pro.tools.http.pojo.HttpReceive in project protools by SeanDragon.

the class DefaultClientPool method request.

public HttpReceive request(HttpSend httpSend, long timeout, TimeUnit timeUnit) {
    final HttpReceive httpReceive = new HttpReceive();
    Future<Channel> fch = channelPool.acquire();
    Channel channel = null;
    try {
        channel = fch.get(timeout, timeUnit);
        ChannelPipeline p = channel.pipeline();
        p.addLast(new HttpClientHandler(httpSend, httpReceive));
        final FullHttpRequest fullHttpRequest = convertRequest(httpSend);
        p.writeAndFlush(fullHttpRequest);
        channel.closeFuture().await(timeout, timeUnit);
        if (!httpReceive.getIsDone()) {
            httpReceive.setHaveError(true);
            httpReceive.setErrMsg("请求已经超时");
        }
    } catch (Exception e) {
        if (log.isWarnEnabled()) {
            log.warn(e.getMessage(), e);
        }
        httpReceive.setHaveError(true).setErrMsg(e.getMessage()).setThrowable(e).setIsDone(true);
    } finally {
        if (channel != null) {
            channelPool.release(channel);
        }
    }
    return httpReceive;
}
Also used : HttpReceive(pro.tools.http.pojo.HttpReceive) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpClientHandler(pro.tools.http.netty.handler.HttpClientHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpException(pro.tools.http.pojo.HttpException) URISyntaxException(java.net.URISyntaxException) SSLException(javax.net.ssl.SSLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

HttpException (pro.tools.http.pojo.HttpException)3 HttpReceive (pro.tools.http.pojo.HttpReceive)3 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 AsyncHttpClient (com.ning.http.client.AsyncHttpClient)1 FluentCaseInsensitiveStringsMap (com.ning.http.client.FluentCaseInsensitiveStringsMap)1 RequestBuilder (com.ning.http.client.RequestBuilder)1 Response (com.ning.http.client.Response)1 Channel (io.netty.channel.Channel)1 ChannelPipeline (io.netty.channel.ChannelPipeline)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)1 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 URL (java.net.URL)1 Charset (java.nio.charset.Charset)1 ExecutionException (java.util.concurrent.ExecutionException)1 SSLException (javax.net.ssl.SSLException)1