本文整理汇总了Java中com.google.appengine.api.urlfetch.HTTPHeader类的典型用法代码示例。如果您正苦于以下问题:Java HTTPHeader类的具体用法?Java HTTPHeader怎么用?Java HTTPHeader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HTTPHeader类属于com.google.appengine.api.urlfetch包,在下文中一共展示了HTTPHeader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: send
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
/**
* @return the response body as a String.
* @throws IOException for 500 or above or general connection problems.
* @throws InvalidStoreRequestException for any response code not 200.
*/
String send(String base) throws IOException {
URL url = new URL(base + urlBuilder.toString());
HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST, getFetchOptions());
// TODO(ohler): use multipart/form-data for efficiency
req.setHeader(new HTTPHeader("Content-Type", "application/x-www-form-urlencoded"));
req.setHeader(new HTTPHeader(WALKAROUND_TRUSTED_HEADER, secret.getHexData()));
// NOTE(danilatos): Appengine will send 503 if the backend is at the
// max number of concurrent requests. We might come up with a use for
// handling this error code specifically. For now, we didn't go through
// the code to make sure that all other overload situations also manifest
// themselves as 503 rather than random exceptions that turn into 500s.
// Therefore, the code in this class treats all 5xx responses as an
// indication of possible overload.
req.setHeader(new HTTPHeader("X-AppEngine-FailFast", "true"));
req.setPayload(contentBuilder.toString().getBytes(Charsets.UTF_8));
log.info("Sending to " + url);
String ret = fetch(req);
log.info("Request completed");
return ret;
}
示例2: setPayloadMultipart
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
/**
* Sets payload on request as a {@code multipart/form-data} request.
*
* <p>This is equivalent to running the command: {@code curl -F [email protected] URL}
*
* @see <a href="http://www.ietf.org/rfc/rfc2388.txt"> RFC2388 - Returning Values from Forms</a>
*/
public static void setPayloadMultipart(
HTTPRequest request, String name, String filename, MediaType contentType, String data) {
String boundary = createMultipartBoundary();
checkState(
!data.contains(boundary),
"Multipart data contains autogenerated boundary: %s", boundary);
StringBuilder multipart = new StringBuilder();
multipart.append(format("--%s\r\n", boundary));
multipart.append(format("%s: form-data; name=\"%s\"; filename=\"%s\"\r\n",
CONTENT_DISPOSITION, name, filename));
multipart.append(format("%s: %s\r\n", CONTENT_TYPE, contentType.toString()));
multipart.append("\r\n");
multipart.append(data);
multipart.append("\r\n");
multipart.append(format("--%s--", boundary));
byte[] payload = multipart.toString().getBytes(UTF_8);
request.addHeader(
new HTTPHeader(CONTENT_TYPE, format("multipart/form-data; boundary=\"%s\"", boundary)));
request.addHeader(new HTTPHeader(CONTENT_LENGTH, Integer.toString(payload.length)));
request.setPayload(payload);
}
示例3: toString
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Override
public String toString() {
StringBuilder res = new StringBuilder(2048 + rsp.getContent().length).append(String.format(
"%s: %s (HTTP Status %d)\nX-Fetch-URL: %s\nX-Final-URL: %s\n",
getClass().getSimpleName(),
getMessage(),
rsp.getResponseCode(),
req.getURL().toString(),
rsp.getFinalUrl()));
for (HTTPHeader header : rsp.getHeadersUncombined()) {
res.append(header.getName());
res.append(": ");
res.append(header.getValue());
res.append('\n');
}
res.append(">>>\n");
res.append(new String(rsp.getContent(), UTF_8));
res.append("\n<<<");
return res.toString();
}
示例4: before
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Before
public void before() throws Exception {
inject.setStaticField(Ofy.class, "clock", clock);
when(fetchService.fetch(any(HTTPRequest.class))).thenReturn(httpResponse);
when(httpResponse.getResponseCode()).thenReturn(SC_ACCEPTED);
when(httpResponse.getHeadersUncombined())
.thenReturn(ImmutableList.of(new HTTPHeader(LOCATION, "http://trololol")));
persistResource(loadRegistrar("TheRegistrar").asBuilder().setIanaIdentifier(99999L).build());
createTld("tld");
persistResource(Registry.get("tld").asBuilder().setLordnUsername("lolcat").build());
lordnRequestInitializer.marksdbLordnPassword = Optional.of("attack");
action.clock = clock;
action.fetchService = fetchService;
action.lordnRequestInitializer = lordnRequestInitializer;
action.phase = "claims";
action.tld = "tld";
action.tmchMarksdbUrl = "http://127.0.0.1";
}
示例5: testSetPayloadMultipart
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Test
public void testSetPayloadMultipart() throws Exception {
HTTPRequest request = mock(HTTPRequest.class);
setPayloadMultipart(
request, "lol", "cat", CSV_UTF_8, "The nice people at the store say hello. ヘ(◕。◕ヘ)");
ArgumentCaptor<HTTPHeader> headerCaptor = ArgumentCaptor.forClass(HTTPHeader.class);
verify(request, times(2)).addHeader(headerCaptor.capture());
List<HTTPHeader> addedHeaders = headerCaptor.getAllValues();
assertThat(addedHeaders.get(0).getName()).isEqualTo(CONTENT_TYPE);
assertThat(addedHeaders.get(0).getValue())
.isEqualTo(
"multipart/form-data; "
+ "boundary=\"------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"");
assertThat(addedHeaders.get(1).getName()).isEqualTo(CONTENT_LENGTH);
assertThat(addedHeaders.get(1).getValue()).isEqualTo("292");
String payload = "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"
+ "Content-Disposition: form-data; name=\"lol\"; filename=\"cat\"\r\n"
+ "Content-Type: text/csv; charset=utf-8\r\n"
+ "\r\n"
+ "The nice people at the store say hello. ヘ(◕。◕ヘ)\r\n"
+ "--------------------------------AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA--";
verify(request).setPayload(payload.getBytes(UTF_8));
verifyNoMoreInteractions(request);
}
示例6: addHeaders
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
private static void addHeaders(HTTPRequest httpRequest,
HttpRequestOptions requestOptions) {
String contentType = requestOptions.getContentType();
if (contentType != null) {
httpRequest.addHeader(new HTTPHeader("Content-Type", contentType));
}
Map<String, String> headers = getRequestHeaders(requestOptions);
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
httpRequest.addHeader(new HTTPHeader(header.getKey(), header.getValue()));
}
}
}
示例7: setRequestProperty
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Override
public void setRequestProperty(final String key,final String value) {
// URLFeth does not allow to modify the following headers:
// - Content-Length
// - Host
// - Vary
// - Via
// - X-Forwarded-For
// - X-ProxyUser-IP
String[] notAllowedHeaders = new String[] {"Content-Length","Host","Vary","Via","X-Forwarded-For","X-ProxyUser-IP"};
if (Strings.of(key).in(notAllowedHeaders)) {
log.warn("GAE does not allow any of theese headers: {}",notAllowedHeaders.toString());
return;
}
if (_requestHeaders == null) _requestHeaders = Sets.newLinkedHashSet();
_requestHeaders.add(new HTTPHeader(key,value));
}
示例8: fetch
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Override
public TransportResponse fetch(final HttpRequest request) throws IOException {
final HTTPRequest gaeRequest = new HTTPRequest(request.toUrl(), HTTPMethod.valueOf(request.getMethod()), defaultOptions());
if (request.getTimeout() > 0)
gaeRequest.getFetchOptions().setDeadline(request.getTimeout() / 1000.0);
for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue()));
}
if (request.getContentType() != null) {
gaeRequest.setHeader(new HTTPHeader("Content-Type", request.getContentType()));
}
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
request.writeBody(outputStream);
if (outputStream.size() > 0) {
gaeRequest.setPayload(outputStream.toByteArray());
}
return new Response(request.getRetries(), gaeRequest);
}
示例9: getCharset
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
private static String getCharset(HTTPResponse p_response)
{
String responseCharset = "UTF-8";
for( HTTPHeader header : p_response.getHeaders() )
{
if( "Content-Type".equalsIgnoreCase( header.getName() ) )
{
Matcher matcher = s_charsetPattern.matcher( header.getValue() );
if( matcher.matches() )
{
responseCharset = matcher.group( 1 );
}
}
}
return responseCharset;
}
示例10: doGet
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
String url = req.getParameter("url");
String deadlineSecs = req.getParameter("deadline");
URLFetchService service = URLFetchServiceFactory.getURLFetchService();
HTTPRequest fetchReq = new HTTPRequest(new URL(url));
if (deadlineSecs != null) {
fetchReq.getFetchOptions().setDeadline(Double.valueOf(deadlineSecs));
}
HTTPResponse fetchRes = service.fetch(fetchReq);
for (HTTPHeader header : fetchRes.getHeaders()) {
res.addHeader(header.getName(), header.getValue());
}
if (fetchRes.getResponseCode() == 200) {
res.getOutputStream().write(fetchRes.getContent());
} else {
res.sendError(fetchRes.getResponseCode(), "Error while fetching");
}
}
示例11: createRawGcsService
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
static RawGcsService createRawGcsService(Map<String, String> headers) {
ImmutableSet.Builder<HTTPHeader> builder = ImmutableSet.builder();
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.add(new HTTPHeader(header.getKey(), header.getValue()));
}
}
RawGcsService rawGcsService;
Value location = SystemProperty.environment.value();
if (location == SystemProperty.Environment.Value.Production || hasCustomAccessTokenProvider()) {
rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
} else if (location == SystemProperty.Environment.Value.Development) {
rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
} else {
Delegate<?> delegate = ApiProxy.getDelegate();
if (delegate == null
|| delegate.getClass().getName().startsWith("com.google.appengine.tools.development")) {
rawGcsService = LocalRawGcsServiceFactory.createLocalRawGcsService();
} else {
rawGcsService = OauthRawGcsServiceFactory.createOauthRawGcsService(builder.build());
}
}
return rawGcsService;
}
示例12: addOptionsHeaders
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
private void addOptionsHeaders(HTTPRequest req, GcsFileOptions options) {
if (options == null) {
return;
}
if (options.getMimeType() != null) {
req.setHeader(new HTTPHeader(CONTENT_TYPE, options.getMimeType()));
}
if (options.getAcl() != null) {
req.setHeader(new HTTPHeader(ACL, options.getAcl()));
}
if (options.getCacheControl() != null) {
req.setHeader(new HTTPHeader(CACHE_CONTROL, options.getCacheControl()));
}
if (options.getContentDisposition() != null) {
req.setHeader(new HTTPHeader(CONTENT_DISPOSITION, options.getContentDisposition()));
}
if (options.getContentEncoding() != null) {
req.setHeader(new HTTPHeader(CONTENT_ENCODING, options.getContentEncoding()));
}
for (Entry<String, String> entry : options.getUserMetadata().entrySet()) {
req.setHeader(new HTTPHeader(X_GOOG_META + entry.getKey(), entry.getValue()));
}
}
示例13: copyObject
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Override
public void copyObject(GcsFilename source, GcsFilename dest, GcsFileOptions fileOptions,
long timeoutMillis) throws IOException {
HTTPRequest req = makeRequest(dest, null, PUT, timeoutMillis);
req.setHeader(new HTTPHeader(X_GOOG_COPY_SOURCE, makePath(source)));
if (fileOptions != null) {
req.setHeader(REPLACE_METADATA_HEADER);
addOptionsHeaders(req, fileOptions);
}
HTTPResponse resp;
try {
resp = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(new HTTPRequestInfo(req), e);
}
if (resp.getResponseCode() != 200) {
throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
}
}
示例14: testDescribeRequestAndResponseF
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
@Test
public void testDescribeRequestAndResponseF() throws Exception {
HTTPRequest request = new HTTPRequest(new URL("http://ping/pong"));
request.setPayload("hello".getBytes());
request.addHeader(new HTTPHeader("k1", "v1"));
request.addHeader(new HTTPHeader("k2", "v2"));
HTTPResponse response = mock(HTTPResponse.class);
when(response.getHeadersUncombined()).thenReturn(ImmutableList.of(new HTTPHeader("k3", "v3")));
when(response.getResponseCode()).thenReturn(500);
when(response.getContent()).thenReturn("bla".getBytes());
String expected = "Request: GET http://ping/pong\nk1: v1\nk2: v2\n\n"
+ "5 bytes of content\n\nResponse: 500 with 3 bytes of content\nk3: v3\nbla\n";
String result =
URLFetchUtils.describeRequestAndResponse(new HTTPRequestInfo(request), response);
assertEquals(expected, result);
}
示例15: makeHttpRequest
import com.google.appengine.api.urlfetch.HTTPHeader; //导入依赖的package包/类
/**
* Creates an HTTPRequest with the information passed in.
*
* @param accessToken the access token necessary to authorize the request.
* @param url the url to query.
* @param payload the payload for the request.
* @return the created HTTP request.
* @throws IOException
*/
public static HTTPResponse makeHttpRequest(
String accessToken, final String url, String payload, HTTPMethod method) throws IOException {
// Create HTTPRequest and set headers
HTTPRequest httpRequest = new HTTPRequest(new URL(url.toString()), method);
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + accessToken));
httpRequest.addHeader(new HTTPHeader("Host", "www.googleapis.com"));
httpRequest.addHeader(new HTTPHeader("Content-Length", Integer.toString(payload.length())));
httpRequest.addHeader(new HTTPHeader("Content-Type", "application/json"));
httpRequest.addHeader(new HTTPHeader("User-Agent", "google-api-java-client/1.0"));
httpRequest.setPayload(payload.getBytes());
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
HTTPResponse httpResponse = fetcher.fetch(httpRequest);
return httpResponse;
}
开发者ID:GoogleCloudPlatform,项目名称:solutions-google-compute-engine-orchestrator,代码行数:26,代码来源:GceApiUtils.java