protected void doHandle(String uriId,HttpUriRequest request,Object result){ if(this.isError(result)){ String content = null; if(request instanceof HttpEntityEnclosingRequestBase){ HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; HttpEntity entity = request_base.getEntity(); //MULTIPART_FORM_DATA 请求类型判断 if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ try { content = EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); } } if(logger.isErrorEnabled()){ logger.error("URI[{}] {} Content:{} Result:{}", uriId, request.getURI(), content == null ? "multipart_form_data" : content, result == null? null : JsonUtil.toJSONString(result)); } } this.handle(uriId,request.getURI().toString(),content,result); } }
@Override public boolean matches(Request request) { try { HttpEntity entity = ((HttpEntityEnclosingRequestBase) request.getHttpRequest()).getEntity(); if (entity == null) { return false; } String message = EntityUtils.toString(entity); return matcher.matches(message); } catch (IOException e) { return false; } }
private void executeCallback(HttpEntityEnclosingRequestBase request, String json, FutureCallback<HttpResponse> httpCallback) { if (json != null && json.length() > 0) { request.addHeader("Content-Type", "application/json"); if (!this.httpCompress) { request.setEntity(generateStringEntity(json)); } else { request.addHeader("Accept-Encoding", "gzip, deflate"); request.setEntity(generateGZIPCompressEntity(json)); } } FutureCallback<HttpResponse> responseCallback = null; if (httpCallback != null) { unCompletedTaskNum.incrementAndGet(); responseCallback = this.httpResponseCallbackFactory.wrapUpBaseHttpFutureCallback(httpCallback); } httpclient.execute(request,responseCallback); }
private HttpRequestBase wrapEntity(SdkHttpFullRequest request, HttpEntityEnclosingRequestBase entityEnclosingRequest) { /* * We should never reuse the entity of the previous request, since * reading from the buffered entity will bypass reading from the * original request content. And if the content contains InputStream * wrappers that were added for validation-purpose (e.g. * Md5DigestCalculationInputStream), these wrappers would never be * read and updated again after AmazonHttpClient resets it in * preparation for the retry. Eventually, these wrappers would * return incorrect validation result. */ if (request.content().isPresent()) { HttpEntity entity = new RepeatableInputStreamRequestEntity(request); if (request.headers().get(HttpHeaders.CONTENT_LENGTH) == null) { entity = ApacheUtils.newBufferedHttpEntity(entity); } entityEnclosingRequest.setEntity(entity); } return entityEnclosingRequest; }
public String syncPut(String url, Header[] headers, HttpEntity entity, String contentType, String defaultEncoding) throws ClientProtocolException, IOException { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPut(url), entity); if (headers != null) request.setHeaders(headers); if (contentType != null) { request.setHeader("Content-Type", contentType); } return parseResponse(syncExec(request), defaultEncoding); }
private HttpClientOauthResponse sendInternal() throws Exception { String urlToGo = getCompleteUrl(); HttpClient client = httpClientProvider.getHttpClient(); // always POST when doing oauth dance on bitbucket // see DefaultAp10Api#getAccessTokenVerb or getRequestTokenVerb HttpRequestBase requestMethod = new HttpPost(); requestMethod.setURI(new URI(urlToGo)); setHeaders(requestMethod); setPayloadParams((HttpEntityEnclosingRequestBase) requestMethod); HttpResponse response = null; response = client.execute(requestMethod); return new HttpClientOauthResponse(response, requestMethod); }
/** * 根据请求信息创建HttpEntityEnclosingRequestBase. * * @param cls 类型Class * @param url URL * @param headers Http请求头信息 * @param params 请求参数列表 * @return HttpEntityEnclosingRequestBase */ protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url, final Map<String, String> headers, final Map<String, String> params) { try { final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url); if (!CollectionUtils.isEmpty(headers)) { headers.forEach((key, value) -> entityBase.addHeader(key, value)); } final List<NameValuePair> pairs = covertParams2Nvps(params); entityBase.setEntity(new UrlEncodedFormEntity(pairs, this.conf.getCharset())); return entityBase; } catch (final Throwable e) { throw new HttpClientInvokeException(e.getMessage(), e); } }
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create(); List<NameValuePair> formParams = new ArrayList<>(); postVariables.forEach((name, values) -> values.forEach(value -> { if (multipart) { if (value.startsWith("@")) { File f = new File(value.substring(1)); multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName()); } else { multipartBuilder.addTextBody(name, value); } } else { formParams.add(new BasicNameValuePair(name, value)); } })); if (multipart) { request.setEntity(multipartBuilder.build()); } else { request.setEntity(new UrlEncodedFormEntity(formParams)); } }
@Test public void testWithBodyMultipleChecksums() throws Exception { final InputStream bodyStream = mock(InputStream.class); testBuilder.body(bodyStream, "plain/text") .digestSha1("checksum") .digestSha256("checksum256") .perform(); final ArgumentCaptor<HttpRequestBase> requestCaptor = ArgumentCaptor.forClass(HttpRequestBase.class); verify(client).executeRequest(eq(uri), requestCaptor.capture()); final HttpEntityEnclosingRequestBase request = (HttpEntityEnclosingRequestBase) requestCaptor.getValue(); final HttpEntity bodyEntity = request.getEntity(); assertEquals(bodyStream, bodyEntity.getContent()); assertEquals("plain/text", request.getFirstHeader(CONTENT_TYPE).getValue()); assertEquals("sha1=checksum, sha256=checksum256", request.getFirstHeader(DIGEST).getValue()); }
@Test public void testWithBody() throws Exception { final InputStream bodyStream = mock(InputStream.class); testBuilder.body(bodyStream, "plain/text") .digestSha1("checksum") .filename("file.txt") .perform(); final ArgumentCaptor<HttpRequestBase> requestCaptor = ArgumentCaptor.forClass(HttpRequestBase.class); verify(client).executeRequest(eq(uri), requestCaptor.capture()); final HttpEntityEnclosingRequestBase request = (HttpEntityEnclosingRequestBase) requestCaptor.getValue(); final HttpEntity bodyEntity = request.getEntity(); assertEquals(bodyStream, bodyEntity.getContent()); assertEquals("plain/text", request.getFirstHeader(CONTENT_TYPE).getValue()); assertEquals("sha1=checksum", request.getFirstHeader(DIGEST).getValue()); assertEquals("attachment; filename=\"file.txt\"", request.getFirstHeader(CONTENT_DISPOSITION).getValue()); }
@Test public void testWithModificationHeaders() throws Exception { final InputStream bodyStream = mock(InputStream.class); final String etag = "123456"; final String lastModified = "Mon, 19 May 2014 19:44:59 GMT"; testBuilder.body(bodyStream, "plain/text") .ifMatch(etag) .ifUnmodifiedSince(lastModified) .perform(); final ArgumentCaptor<HttpRequestBase> requestCaptor = ArgumentCaptor.forClass(HttpRequestBase.class); verify(client).executeRequest(eq(uri), requestCaptor.capture()); final HttpEntityEnclosingRequestBase request = (HttpEntityEnclosingRequestBase) requestCaptor.getValue(); final HttpEntity bodyEntity = request.getEntity(); assertEquals(bodyStream, bodyEntity.getContent()); assertEquals("plain/text", request.getFirstHeader(CONTENT_TYPE).getValue()); assertEquals(etag, request.getFirstHeader(IF_MATCH).getValue()); assertEquals(lastModified, request.getFirstHeader(IF_UNMODIFIED_SINCE).getValue()); }
@Override void buildBodyParameters(HttpRequestBase request) { List<NameValuePair> fields = new ArrayList<NameValuePair>(); for (Node field : getFormParams()) { String name = XMLCrawler.getAttributeValue("name", field); String value = XMLCrawler.getAttributeValue("value", field); // System.out.println(name+"="+value); NameValuePair nvp = new BasicNameValuePair(name, value); fields.add(nvp); } try { ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(fields)); } catch (UnsupportedEncodingException e) { System.out.println("Error encoding URL." + e.getMessage()); } }
public static HttpEntityEnclosingRequestBase getHTTPPatch(String url) throws PageException { // try to load the class, perhaps class does not exists with older jars Class clazz = ClassUtil.loadClass( HttpEntityEnclosingRequestBase.class.getClassLoader(), "org.apache.http.client.methods.HttpPatch",null); if(clazz==null) throw new ApplicationException("cannot load class [org.apache.http.client.methods.HttpPatch], you have to update your apache-commons-http*** jars"); try { return (HttpEntityEnclosingRequestBase) ClassUtil.loadInstance(clazz,new Object[]{url}); } catch(Throwable t) { ExceptionUtil.rethrowIfNecessary(t); throw Caster.toPageException(t); } //FUTURE if we have the new jar for sure return new HttpPatch(url); }
/** * 如果request的请求体不为空,进行设置请求体信息 * @param httpRequest * @param request * @throws AuthFailureError */ private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } }
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } }
private static HttpRequestBase addRequestBody(HttpRequestBase httpRequest, HttpEntity entity) { if (entity != null) { if (httpRequest instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase)httpRequest).setEntity(entity); } else { throw new UnsupportedOperationException(httpRequest.getMethod() + " with body is not supported"); } } return httpRequest; }
/** * 日志记录 * @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 HttpEntityEnclosingRequestBase){ HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; HttpEntity entity = request_base.getEntity(); String content = null; //MULTIPART_FORM_DATA 请求类型判断 if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ try { content = EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } } logger.info("URI[{}] {} {} ContentLength:{} Content:{}", id, request.getURI().toString(), entity.getContentType(), entity.getContentLength(), content == null?"multipart_form_data":content); }else{ logger.info("URI[{}] {}",id,request.getURI().toString()); } } return id; }
private Action echo() { return r -> { HttpEntity entity = ((HttpEntityEnclosingRequestBase) r.getHttpRequest()).getEntity(); BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "ok"); response.setEntity(entity); return response; }; }
public void post(Context context, String url, Header[] headers, RequestParams params, String contentType, AsyncHttpResponseHandler responseHandler) { HttpEntityEnclosingRequestBase request = new HttpPost(url); if (params != null) { request.setEntity(paramsToEntity(params)); } if (headers != null) { request.setHeaders(headers); } sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
public void post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity); if (headers != null) { request.setHeaders(headers); } sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
public void put(Context context, String url, Header[] headers, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPut(url), entity); if (headers != null) { request.setHeaders(headers); } sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
/** Executes the request and extracts the string from the * response body if there is one. */ public ClientResponse execute() { try { if (Http.Methods.GET.equals(method)) { this.apacheRequest = new HttpGet(url); } else if (Http.Methods.POST.equals(method)) { this.apacheRequest = new HttpPost(url); } else if (Http.Methods.PUT.equals(method)) { this.apacheRequest = new HttpPost(url); } else if (Http.Methods.DELETE.equals(method)) { this.apacheRequest = new HttpPost(url); } else { throw new RuntimeException("Invalid HTTP method "+method+" for request "+url); } if (headers!=null) { for (String headerName: headers.keySet()) { for (String headerValue: headers.get(headerName)) { apacheRequest.addHeader(headerName, headerValue); } } } if (body!=null) { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase)apacheRequest).setEntity(entity); } return createHttpResponse(); } catch (IOException e) { throw new RuntimeException("Couldn't execute request "+url+": "+e.getMessage(), e); } }
public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = new HttpPost(getURI(url)); if (params != null) { request.setEntity(paramsToEntity(params, responseHandler)); } if (headers != null) { request.setHeaders(headers); } return sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
public RequestHandle post(Context context, String url, Header[] headers, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(getURI(url)) , entity); if (headers != null) { request.setHeaders(headers); } return sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
public RequestHandle put(Context context, String url, Header[] headers, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPut(getURI(url)), entity); if (headers != null) { request.setHeaders(headers); } return sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
public RequestHandle patch(Context context, String url, Header[] headers, HttpEntity entity, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPatch(getURI(url) ), entity); if (headers != null) { request.setHeaders(headers); } return sendRequest(this.httpClient, this.httpContext, request, contentType, responseHandler, context); }
private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { if (entity != null) { requestBase.setEntity(entity); } return requestBase; }
/** * Applicable only to HttpRequest methods extending * HttpEntityEnclosingRequestBase, which is for example not DELETE * * @param entity entity to be included within the request * @param requestBase HttpRequest instance, must not be null */ private HttpEntityEnclosingRequestBase addEntityToRequestBase( HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { if (entity != null) { requestBase.setEntity(entity); } return requestBase; }
/** * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for * example not DELETE * * @param entity entity to be included within the request * @param requestBase HttpRequest instance, must not be null */ private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { if (entity != null) { requestBase.setEntity(entity); } return requestBase; }
public static void setMethodAttributes(HttpEntityEnclosingRequestBase method, Request request) { if(request.getBody() != null) { method.setEntity(new ByteArrayEntity(request.getBody())); } if (request.getParts() != null) { HttpEntity re = createMultipartEntities(request.getMultipartMode(), request.getParts()); method.setEntity(re); } setMethodAttributes((HttpRequestBase) method, request); }
private HttpRequestBase wrapEntity(Request<?> request, HttpEntityEnclosingRequestBase entityEnclosingRequest, String encodedParams) throws FakeIOException { if (HttpMethodName.POST == request.getHttpMethod()) { /* * If there isn't any payload content to include in this request, * then try to include the POST parameters in the query body, * otherwise, just use the query string. For all AWS Query services, * the best behavior is putting the params in the request body for * POST requests, but we can't do that for S3. */ if (request.getContent() == null && encodedParams != null) { entityEnclosingRequest.setEntity(ApacheUtils.newStringEntity(encodedParams)); } else { entityEnclosingRequest.setEntity(new RepeatableInputStreamRequestEntity(request)); } } else { /* * We should never reuse the entity of the previous request, since * reading from the buffered entity will bypass reading from the * original request content. And if the content contains InputStream * wrappers that were added for validation-purpose (e.g. * Md5DigestCalculationInputStream), these wrappers would never be * read and updated again after AmazonHttpClient resets it in * preparation for the retry. Eventually, these wrappers would * return incorrect validation result. */ if (request.getContent() != null) { HttpEntity entity = new RepeatableInputStreamRequestEntity(request); if (request.getHeaders().get(HttpHeaders.CONTENT_LENGTH) == null) { entity = ApacheUtils.newBufferedHttpEntity(entity); } entityEnclosingRequest.setEntity(entity); } } return entityEnclosingRequest; }