本文整理汇总了Java中com.google.appengine.api.urlfetch.HTTPMethod类的典型用法代码示例。如果您正苦于以下问题:Java HTTPMethod类的具体用法?Java HTTPMethod怎么用?Java HTTPMethod使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HTTPMethod类属于com.google.appengine.api.urlfetch包,在下文中一共展示了HTTPMethod类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processRequestBody
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
private void processRequestBody() {
if (getMethod().equalsIgnoreCase(HTTPMethod.GET.name())) {
return;
}
body = readBodyFromRequest(servletRequest);
if (body == null || body.length() < 1) {
return;
}
try {
JsonParser jsonParser = new JsonParser();
jsonBody = (JsonObject) jsonParser.parse(body);
// add primitives from json body as request parameters
for (Entry<String, JsonElement> jsonElementEntry : jsonBody.entrySet()) {
if (jsonElementEntry.getValue().isJsonPrimitive()) {
addParameter(jsonElementEntry.getKey(), jsonElementEntry.getValue().getAsString());
}
}
} catch (Exception e) {
log.warning("Unable to process request body: " + e.getMessage());
}
}
示例2: doGet
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String photoId = requireParameter(req, "photoId");
// http://code.google.com/apis/contacts/docs/2.0/developers_guide_protocol.html#groups_feed_url
// says "You can also substitute 'default' for the user's email address,
// which tells the server to return the contact groups for the user whose
// credentials accompany the request". I didn't read the document in enough
// detail to check whether this is supposed to apply to photos as well, but
// it seems to work.
URL targetUrl = new URL("https://www.google.com/m8/feeds/photos/media/default/"
+ UriEscapers.uriQueryStringEscaper(false).escape(photoId));
HTTPResponse response = fetch.fetch(
new HTTPRequest(targetUrl, HTTPMethod.GET,
FetchOptions.Builder.withDefaults().disallowTruncate()));
if (response.getResponseCode() == 404) {
// Rather than a broken image, use the unknown avatar.
log.info("Missing image, using default");
resp.sendRedirect(SharedConstants.UNKNOWN_AVATAR_URL);
} else {
ProxyHandler.copyResponse(response, resp);
}
// TODO(hearnden): Do something to make the client cache photos sensibly.
}
示例3: proxy
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
private void proxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (!req.getRequestURI().startsWith(sourceUriPrefix)) {
log.info("Not proxying request to " + req.getRequestURI()
+ ", does not start with " + sourceUriPrefix);
return;
}
String sourceUri = req.getRequestURI();
String query = req.getQueryString() != null ? req.getQueryString() : "";
String targetUri = targetUriPrefix + sourceUri.substring(sourceUriPrefix.length()) + query;
log.info("Forwarding request: " + sourceUri + query + " to " + targetUri);
HTTPMethod fetchMethod = HTTPMethod.valueOf(req.getMethod());
HTTPRequest fetchRequest = new HTTPRequest(new URL(targetUri), fetchMethod);
fetchRequest.setPayload(copy(req.getInputStream(), new ByteArrayOutputStream()).toByteArray());
HTTPResponse fetchResponse = fetch.fetch(fetchRequest);
copyResponse(fetchResponse, resp);
}
示例4: send
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的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;
}
示例5: getRequestMethod
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
@Override
public String getRequestMethod() {
String outMethod = "unknown";
if (_requestMethod == HTTPMethod.GET) {
outMethod = "GET";
} else if (_requestMethod == HTTPMethod.PUT) {
outMethod = "PUT";
} else if (_requestMethod == HTTPMethod.POST) {
outMethod = "POST";
} else if (_requestMethod == HTTPMethod.HEAD) {
outMethod = "HEAD";
} else if (_requestMethod == HTTPMethod.DELETE) {
outMethod = "DELETE";
}
return outMethod;
}
示例6: fetch
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的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);
}
示例7: curl
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
public static byte[] curl (String endpoint, byte[] payload,
HTTPMethod method) {
byte[] content = null;
if (LOG.isLoggable(Level.FINE)) {
LOG.log(Level.FINE, String.format(
"calling endpoint [%s] with payload [%s] using method [%s]",
endpoint, payload == null ? null : new String(payload),
method.toString()));
}
try {
URL url = new URL(endpoint);
content = curl(url, payload, method);
} catch (MalformedURLException e) {
if (LOG.isLoggable(Level.SEVERE)) {
LOG.log(Level.SEVERE, String.format(
"Error creating url from endpoint [%s]", endpoint), e);
}
}
return content;
}
示例8: trackEventToGoogleAnalytics
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
/**
* Posts an Event Tracking message to Google Analytics.
*
* @param category the required event category
* @param action the required event action
* @param label the optional event label
* @param value the optional value
* @return true if the call succeeded, otherwise false
* @exception IOException if the URL could not be posted to
*/
public int trackEventToGoogleAnalytics(
String category, String action, String label, String value) throws IOException {
Map<String, String> map = new LinkedHashMap<>();
map.put("v", "1"); // Version.
map.put("tid", gaTrackingId);
map.put("cid", gaClientId);
map.put("t", "event"); // Event hit type.
map.put("ec", encode(category, true));
map.put("ea", encode(action, true));
map.put("el", encode(label, false));
map.put("ev", encode(value, false));
HTTPRequest request = new HTTPRequest(GA_URL_ENDPOINT, HTTPMethod.POST);
request.addHeader(CONTENT_TYPE_HEADER);
request.setPayload(getPostData(map));
HTTPResponse httpResponse = urlFetchService.fetch(request);
// Return True if the call was successful.
return httpResponse.getResponseCode();
}
开发者ID:GoogleCloudPlatform,项目名称:appengine-googleanalytics-java,代码行数:31,代码来源:GoogleAnalyticsTracking.java
示例9: getResponseDELETE
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
public static String getResponseDELETE(String url, Map<String, String> params, Map<String, String> headers) {
int retry = 0;
while (retry < 3) {
long start = System.currentTimeMillis();
try {
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
String urlStr = ToolString.toUrl(url.trim(), params);
logger.debug("DELETE : " + urlStr);
HTTPRequest httpRequest = new HTTPRequest(new URL(urlStr), HTTPMethod.DELETE, FetchOptions.Builder.withDeadline(deadline));
HTTPResponse response = fetcher.fetch(httpRequest);
return processResponse(response);
} catch (Throwable e) {
retry++;
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (retry < 3) {
logger.warn("retrying after " + (System.currentTimeMillis() - start) + " and " + retry + " retries\n" + e.getClass() + e.getMessage());
} else {
logger.error(e.getClass() + "\n" + ToolString.stack2string(e));
}
}
}
return null;
}
示例10: getResponseProxyPOST
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
public static String getResponseProxyPOST(URL url) throws MalformedURLException, UnsupportedEncodingException, IOException {
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
String base64payload = "base64url=" + Base64UrlSafe.encodeServer(url.toString());
String urlStr = url.toString();
if (urlStr.contains("?")) {
base64payload = "base64url=" + Base64UrlSafe.encodeServer(urlStr.substring(0, urlStr.indexOf("?")));
base64payload += "&base64content=" + Base64UrlSafe.encodeServer(urlStr.substring(urlStr.indexOf("?") + 1));
} else {
base64payload = "base64url=" + Base64UrlSafe.encodeServer(urlStr);
}
HTTPRequest httpRequest = new HTTPRequest(new URL(HttpClientGAE.POSTPROXY_PHP), HTTPMethod.POST, FetchOptions.Builder.withDeadline(30d).doNotValidateCertificate());
httpRequest.setPayload(base64payload.getBytes(UTF8));
HTTPResponse response = fetcher.fetch(httpRequest);
String processResponse = HttpClientGAE.processResponse(response);
logger.info("proxying " + url + "\nprocessResponse:" + processResponse);
return processResponse;
}
示例11: createInstance
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
/**
* Creates a new instance.
*
* @param instanceName the name of the instance to create.
* @param bootDiskName the name of the disk to create the instance with.
* @param projectApiKey the project API key.
* @param accessToken the access token.
* @param configProperties the configuration properties.
* @throws MalformedURLException
* @throws IOException
* @throws OrchestratorException if the REST API call failed to create instance.
*/
private void createInstance(String instanceName, String bootDiskName, String projectApiKey,
String accessToken, Map<String, String> configProperties)
throws MalformedURLException, IOException, OrchestratorException {
String url = GceApiUtils.composeInstanceApiUrl(
ConfigProperties.urlPrefixWithProjectAndZone, projectApiKey);
String payload = createPayload_instance(instanceName, bootDiskName, configProperties);
logger.info(
"Calling " + url + " to create instance " + instanceName + "with payload " + payload);
HTTPResponse httpResponse =
GceApiUtils.makeHttpRequest(accessToken, url, payload, HTTPMethod.POST);
int responseCode = httpResponse.getResponseCode();
if (!(responseCode == 200 || responseCode == 204)) {
throw new OrchestratorException("Failed to create GCE instance. " + instanceName
+ ". Response code " + responseCode + " Reason: "
+ new String(httpResponse.getContent()));
}
}
开发者ID:GoogleCloudPlatform,项目名称:solutions-google-compute-engine-orchestrator,代码行数:30,代码来源:GceInstanceCreator.java
示例12: checkDiskOrInstance
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
/**
* Checks whether the disk or instance is available.
*
* @param accessToken the access token.
* @param url the URL to check whether the disk/instance has been created.
* @return true if the disk/instance is available, false otherwise.
* @throws MalformedURLException
* @throws IOException
*/
private boolean checkDiskOrInstance(String accessToken, String url)
throws MalformedURLException, IOException {
HTTPResponse httpResponse = GceApiUtils.makeHttpRequest(accessToken, url, "", HTTPMethod.GET);
int responseCode = httpResponse.getResponseCode();
if (!(responseCode == 200 || responseCode == 204)) {
logger.fine("Disk/instance not ready. Response code " + responseCode + " Reason: "
+ new String(httpResponse.getContent()));
return false;
}
// Check if the disk/instance is in status "READY".
String contentStr = new String(httpResponse.getContent());
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject) parser.parse(contentStr);
String status = o.get("status").getAsString();
if (!status.equals("READY") && !status.equals("RUNNING")) {
return false;
}
return true;
}
开发者ID:GoogleCloudPlatform,项目名称:solutions-google-compute-engine-orchestrator,代码行数:29,代码来源:GceInstanceCreator.java
示例13: makeHttpRequest
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的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
示例14: deleteInstance
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
/**
* Deletes an instance.
*
* @param name the name of the instance to delete.
* @throws OrchestratorException if delete failed.
*/
private void deleteInstance(String name, String accessToken, String url)
throws OrchestratorException {
logger.info("Shutting down instance: " + name);
HTTPResponse httpResponse;
try {
httpResponse = GceApiUtils.makeHttpRequest(accessToken, url, "", HTTPMethod.DELETE);
int responseCode = httpResponse.getResponseCode();
if (!(responseCode == 200 || responseCode == 204)) {
throw new OrchestratorException("Delete Instance failed. Response code " + responseCode
+ " Reason: " + new String(httpResponse.getContent()));
}
} catch (IOException e) {
throw new OrchestratorException(e);
}
}
开发者ID:GoogleCloudPlatform,项目名称:solutions-google-compute-engine-orchestrator,代码行数:22,代码来源:GceInstanceDestroyer.java
示例15: fetch
import com.google.appengine.api.urlfetch.HTTPMethod; //导入依赖的package包/类
private HttpResponse fetch(String url, HttpRequestOptions requestOptions,
HTTPMethod method, String content) throws IOException {
final FetchOptions options = getFetchOptions(requestOptions);
String currentUrl = url;
for (int i = 0; i <= requestOptions.getMaxRedirects(); i++) {
HTTPRequest httpRequest = new HTTPRequest(new URL(currentUrl),
method, options);
addHeaders(httpRequest, requestOptions);
if (method == HTTPMethod.POST && content != null) {
httpRequest.setPayload(content.getBytes());
}
HTTPResponse httpResponse;
try {
httpResponse = fetchService.fetch(httpRequest);
} catch (ResponseTooLargeException e) {
return new TooLargeResponse(currentUrl);
}
if (!isRedirect(httpResponse.getResponseCode())) {
boolean isResponseTooLarge =
(getContentLength(httpResponse) > requestOptions.getMaxBodySize());
return new AppEngineFetchResponse(httpResponse,
isResponseTooLarge, currentUrl);
} else {
currentUrl = getResponseHeader(httpResponse, "Location").getValue();
}
}
throw new IOException("exceeded maximum number of redirects");
}