/** * Add payload to request. By default, payload is sent as application/json */ protected int addPayload(RequestBuilder builder, String payload) { if (payload == null || payload.length() == 0) { return 0; } builder.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getMimeType()); builder.setEntity(new StringEntity(payload, contentType)); return payload.length(); }
String content = null; if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ try { content = EntityUtils.toString(entity);
public MultipartBody field(String name, InputStream stream, String fileName) { return field(name, new InputStreamBody(stream, ContentType.APPLICATION_OCTET_STREAM, fileName), true, ContentType.APPLICATION_OCTET_STREAM.getMimeType()); }
public MultipartBody field(String name, byte[] bytes, String fileName) { return field(name, new ByteArrayBody(bytes, ContentType.APPLICATION_OCTET_STREAM, fileName), true, ContentType.APPLICATION_OCTET_STREAM.getMimeType()); }
public MultipartBody field(String name, InputStream stream, ContentType contentType, String fileName) { return field(name, new InputStreamBody(stream, contentType, fileName), true, contentType.getMimeType()); }
public MultipartBody field(String name, byte[] bytes, ContentType contentType, String fileName) { return field(name, new ByteArrayBody(bytes, contentType, fileName), true, contentType.getMimeType()); }
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) { logger.error("", e); } } 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); } }
protected HttpEntity buildPostRequestEntity(CrawlURI curi) { String enctype = (String) curi.getData().get(CoreAttributeConstants.A_SUBMIT_ENCTYPE); if (enctype == null) { enctype = ContentType.APPLICATION_FORM_URLENCODED.getMimeType(); } @SuppressWarnings("unchecked") List<NameValue> submitData = (List<NameValue>) curi.getData().get(CoreAttributeConstants.A_SUBMIT_DATA); if (enctype.equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { LinkedList<NameValuePair> nvps = new LinkedList<NameValuePair>(); for (NameValue nv: submitData) { nvps.add(new BasicNameValuePair(nv.name, nv.value)); } try { return new UrlEncodedFormEntity(nvps, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else if (enctype.equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) { MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (NameValue nv: submitData) { entityBuilder.addTextBody(escapeForMultipart(nv.name), escapeForMultipart(nv.value)); } return entityBuilder.build(); } else { throw new IllegalStateException("unsupported form submission enctype='" + enctype + "'"); } }
private HttpUriRequest newRequest(RequestBuilder builder, JsonElement payload) { try { builder.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .addHeader(HttpHeaders.AUTHORIZATION, "OAuth " + accessToken) .setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); } catch (Exception e) { throw new RuntimeException(e); } if (getLog().isDebugEnabled()) { getLog().debug("Request builder: " + ToStringBuilder.reflectionToString(builder, ToStringStyle.SHORT_PREFIX_STYLE)); } return builder.build(); }
ContentType contentType = ContentType.get(response.getEntity()); String contentTypeStr = contentType==null?null:contentType.getMimeType(); if(contentType != null && (ContentType.TEXT_PLAIN.getMimeType().equalsIgnoreCase(contentTypeStr) ||ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentTypeStr))){ HttpEntity entity = response.getEntity(); String str = EntityUtils.toString(entity,"utf-8");
@Override public Optional<HttpUriRequest> onNewRecord(D record) { try { HttpUriRequest uriRequest = RequestBuilder.post() .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()) .setUri(getCurServerHost()) .setEntity(new StringEntity(record.toString(), ContentType.TEXT_PLAIN.toString())) .build(); return Optional.of(uriRequest); } catch (Exception e) { throw new RuntimeException(e); } }
if (contentTypeHeader != null && contentTypeHeader.length > 0) { if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); throw new WxErrorException(WxError.fromJson(responseContent));
if (contentTypeHeader != null && contentTypeHeader.length > 0) { if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) { String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); throw new WxErrorException(WxError.fromJson(responseContent));
@Override public Optional<HttpUriRequest> onNewRecord(RestEntry<JsonObject> record) { HttpUriRequest uriRequest = RequestBuilder.post() .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .setUri(combineUrl(getCurServerHost(), record.getResourcePath())) .setEntity(new StringEntity(record.getRestEntryVal().toString(), ContentType.APPLICATION_JSON)) .build(); return Optional.of(uriRequest); } }
@Override public Optional<HttpUriRequest> onNewRecord(RestEntry<String> record) { HttpUriRequest uriRequest = RequestBuilder.post() .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()) .setUri(combineUrl(getCurServerHost(), record.getResourcePath())) .setEntity(new StringEntity(record.getRestEntryVal(), ContentType.TEXT_PLAIN)) .build(); return Optional.of(uriRequest); } }
reqEntity.setContentType( map(fromFormat).getMimeType() ); // messy that API is different to FileEntity reqEntity.setContent(instream);
/** * Build a {@link HttpUriRequest} from a {@link GenericRecord} */ public void testBuildWriteRequest() throws IOException { String urlTemplate = "http://www.test.com/a/part1:${part1}/a/part2:${part2}"; String verb = "post"; ApacheHttpRequestBuilder builder = spy(new ApacheHttpRequestBuilder(urlTemplate, verb, "application/json")); ArgumentCaptor<RequestBuilder> requestBuilderArgument = ArgumentCaptor.forClass(RequestBuilder.class); Queue<BufferedRecord<GenericRecord>> queue = HttpTestUtils.createQueue(1, false); AsyncRequest<GenericRecord, HttpUriRequest> request = builder.buildRequest(queue); verify(builder).build(requestBuilderArgument.capture()); RequestBuilder expected = RequestBuilder.post(); expected.setUri("http://www.test.com/a/part1:01/a/part2:02?param1=01"); String payloadStr = "{\"id\":\"id0\"}"; expected.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .setEntity(new StringEntity(payloadStr, ContentType.APPLICATION_JSON)); // Compare HttpUriRequest HttpTestUtils.assertEqual(requestBuilderArgument.getValue(), expected); Assert.assertEquals(request.getRecordCount(), 1); Assert.assertEquals(queue.size(), 0); } }
/** * 检测响应类型是否为json * @param contentType 内容类型 * @param textFirst 文本第一个字符 * @return 布尔型, true为json内容类型 */ private boolean isJson(String contentType, String textFirst){ return( ContentType.APPLICATION_JSON.getMimeType().equals(contentType) || "{[".indexOf(textFirst) >= 0 ); } /**
/** * 检测响应类型是否为xml * @param contentType 内容类型 * @param textFirst 文本第一个字符 * @return 布尔型, true为xml内容类型 */ private boolean isXml(String contentType, String textFirst){ return( ContentType.APPLICATION_XML.getMimeType().equals(contentType) || "<".indexOf(textFirst) >= 0 ); }
@Override public String getMimeType() { ContentType ct = ContentType.get(myResponse.getEntity()); return ct != null ? ct.getMimeType() : null; }