本文整理汇总了Java中org.apache.http.client.methods.HttpEntityEnclosingRequestBase.setHeader方法的典型用法代码示例。如果您正苦于以下问题:Java HttpEntityEnclosingRequestBase.setHeader方法的具体用法?Java HttpEntityEnclosingRequestBase.setHeader怎么用?Java HttpEntityEnclosingRequestBase.setHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.client.methods.HttpEntityEnclosingRequestBase
的用法示例。
在下文中一共展示了HttpEntityEnclosingRequestBase.setHeader方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: syncPut
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
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);
}
示例2: syncPost
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
public String syncPost(String url, Header[] headers, HttpEntity entity, String contentType, String defaultEncoding)
throws ClientProtocolException, IOException {
HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPost(url), entity);
if (headers != null)
request.setHeaders(headers);
if (contentType != null) {
request.setHeader("Content-Type", contentType);
}
return parseResponse(syncExec(request), defaultEncoding);
}
示例3: completeRequest
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
/** helper function to fill the request with header entries and posting body .
* */
private static HttpEntityEnclosingRequestBase completeRequest(HttpEntityEnclosingRequestBase request,
List<NameValuePair> headerEntries,
String postingBody) throws UnsupportedEncodingException{
if (null != completeRequest(request, headerEntries)){
// dump the post body UTF-8 will be used as the default encoding type.
if (null != postingBody && postingBody.length() > 0){
HttpEntity entity = new ByteArrayEntity(postingBody.getBytes("UTF-8"));
request.setHeader("Content-Length", Long.toString(entity.getContentLength()));
request.setEntity(entity);
}
}
return request;
}
示例4: setHttpHeaders
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
/**
* Set the HTTP Headers required for the request
* @param httpPost
* @param payload
* @param requestOptions
* @throws Exception
*/
private void setHttpHeaders(HttpEntityEnclosingRequestBase httpPost, String payload, PayeezyRequestOptions requestOptions) throws Exception{
Map<String, String> keyMap = getSecurityKeys( payload, requestOptions);
Iterator<String> iter=keyMap.keySet().iterator();
while(iter.hasNext()) {
String key=iter.next();
if(APIResourceConstants.SecurityConstants.PAYLOAD.equals(key))
continue;
httpPost.setHeader(key, keyMap.get(key));
}
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
}
示例5: sendJsonPostOrPut
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
private Response sendJsonPostOrPut(OauthToken token, String url, String json,
int connectTimeout, int readTimeout, String method) throws IOException {
LOG.debug("Sending JSON " + method + " to URL: " + url);
Response response = new Response();
HttpClient httpClient = createHttpClient(connectTimeout, readTimeout);
HttpEntityEnclosingRequestBase action;
if("POST".equals(method)) {
action = new HttpPost(url);
} else if("PUT".equals(method)) {
action = new HttpPut(url);
} else {
throw new IllegalArgumentException("Method must be either POST or PUT");
}
Long beginTime = System.currentTimeMillis();
action.setHeader("Authorization", "Bearer" + " " + token.getAccessToken());
StringEntity requestBody = new StringEntity(json, ContentType.APPLICATION_JSON);
action.setEntity(requestBody);
HttpResponse httpResponse = httpClient.execute(action);
String content = handleResponse(httpResponse, action);
response.setContent(content);
response.setResponseCode(httpResponse.getStatusLine().getStatusCode());
Long endTime = System.currentTimeMillis();
LOG.debug("POST call took: " + (endTime - beginTime) + "ms");
return response;
}
示例6: put
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
@Override
public URI put(final WebResource resource, final boolean asBinary) {
init.await();
HttpEntityEnclosingRequestBase request = null;
if (resource.uri() == null || !resource.uri().isAbsolute()) {
request = new HttpPost(containerId);
final String name = slugText(resource);
if (name != null) {
request.addHeader("Slug", name);
}
if (asBinary) {
request.addHeader("Content-Disposition",
String.format("attachment; filename=%s", name != null ? name : "file.bin"));
}
} else {
request = new HttpPut(resource.uri());
if (!asBinary) {
request.addHeader("Prefer", "handling=lenient; received=\"minimal\"");
}
}
if (resource.representation() != null) {
request.setEntity(new InputStreamEntity(resource.representation()));
}
request.setHeader(HttpHeaders.CONTENT_TYPE, resource.contentType());
try {
return client.execute(request, (response -> {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_CREATED) {
return URI.create(response.getFirstHeader(HttpHeaders.LOCATION).getValue());
} else if (status == HttpStatus.SC_NO_CONTENT || status == HttpStatus.SC_OK) {
return resource.uri();
} else {
throw new RuntimeException(String.format("Resource creation failed: %s; %s",
response.getStatusLine().toString(),
EntityUtils.toString(response.getEntity())));
}
}));
} catch (final Exception e) {
throw new RuntimeException(String.format("Error executing %s request to %s", request.getClass()
.getSimpleName(), request.getURI().toString()), e);
}
}
示例7: sendEntityData
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
/**
* Creates the entity data to be sent.
* <p>
* If there is a file entry with a non-empty MIME type we use that to
* set the request Content-Type header, otherwise we default to whatever
* header is present from a Header Manager.
* <p>
* If the content charset {@link #getContentEncoding()} is null or empty
* we use the HC4 default provided by {@link HTTP#DEF_CONTENT_CHARSET} which is
* ISO-8859-1.
*
* @param entity to be processed, e.g. PUT or PATCH
* @return the entity content, may be empty
* @throws UnsupportedEncodingException for invalid charset name
* @throws IOException cannot really occur for ByteArrayOutputStream methods
*/
protected String sendEntityData( HttpEntityEnclosingRequestBase entity) throws IOException {
// Buffer to hold the entity body
StringBuilder entityBody = new StringBuilder(1000);
boolean hasEntityBody = false;
final HTTPFileArg[] files = getHTTPFiles();
// Allow the mimetype of the file to control the content type
// This is not obvious in GUI if you are not uploading any files,
// but just sending the content of nameless parameters
final HTTPFileArg file = files.length > 0? files[0] : null;
String contentTypeValue = null;
if(file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
contentTypeValue = file.getMimeType();
entity.setHeader(HEADER_CONTENT_TYPE, contentTypeValue); // we provide the MIME type here
}
// Check for local contentEncoding (charset) override; fall back to default for content body
// we do this here rather so we can use the same charset to retrieve the data
final String charset = getContentEncoding(HTTP.DEF_CONTENT_CHARSET.name());
// Only create this if we are overriding whatever default there may be
// If there are no arguments, we can send a file as the body of the request
if(!hasArguments() && getSendFileAsPostBody()) {
hasEntityBody = true;
// If getSendFileAsPostBody returned true, it's sure that file is not null
File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
FileEntity fileRequestEntity = new FileEntity(reservedFile); // no need for content-type here
entity.setEntity(fileRequestEntity);
}
// If none of the arguments have a name specified, we
// just send all the values as the entity body
else if(getSendParameterValuesAsPostBody()) {
hasEntityBody = true;
// Just append all the parameter values, and use that as the entity body
StringBuilder entityBodyContent = new StringBuilder();
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (charset != null) {
entityBodyContent.append(arg.getEncodedValue(charset));
} else {
entityBodyContent.append(arg.getEncodedValue());
}
}
StringEntity requestEntity = new StringEntity(entityBodyContent.toString(), charset);
entity.setEntity(requestEntity);
}
// Check if we have any content to send for body
if(hasEntityBody) {
// If the request entity is repeatable, we can send it first to
// our own stream, so we can return it
final HttpEntity entityEntry = entity.getEntity();
if(entityEntry.isRepeatable()) {
entityBody.append("<actual file content, not shown here>");
}
else { // this probably cannot happen
entityBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
}
}
return entityBody.toString(); // may be the empty string
}
示例8: fillRequestEntity
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; //导入方法依赖的package包/类
private void fillRequestEntity(HttpEntityEnclosingRequestBase base, Request request) {
if (request.hasEntity()) {
HttpEntity entity;
ContentType contentType = request.getContentType();
switch (contentType) {
case APPLICATION_JSON:
case APPLICATION_JSON_PATCH:
String textEntity = converter.resourceToJson(request.getEntity(),
config.getOneViewApiVersion().getValue());
entity = EntityBuilder.create()
.setContentType(toApacheContentType(contentType))
.setText(textEntity)
.build();
break;
case TEXT_PLAIN:
entity = EntityBuilder.create()
.setContentType(toApacheContentType(contentType))
.setText(request.getEntity().toString())
.build();
break;
case MULTIPART_FORM_DATA:
Object content = request.getEntity();
if (content instanceof GoldenImageFile) {
GoldenImageFile goldenImageFile = (GoldenImageFile) request.getEntity();
entity = MultipartEntityBuilder.create()
.setContentType(toApacheContentType(contentType))
.addBinaryBody("file", goldenImageFile.getFile())
.addTextBody("name", goldenImageFile.getName())
.addTextBody("description", goldenImageFile.getDescription())
.build();
} else {
File file = (File) request.getEntity();
entity = MultipartEntityBuilder.create()
.setContentType(toApacheContentType(contentType))
.addBinaryBody("file", file)
.build();
//TODO add support for custom headers in Request object
base.setHeader("uploadfilename", file.getName());
}
break;
default:
LOGGER.error("Unsupported entity Content-Type " + contentType.toString());
throw new SDKInvalidArgumentException(SDKErrorEnum.internalServerError,
"Unsupported entity Content-Type " + contentType.toString());
}
base.setEntity(entity);
}
}