本文整理汇总了Java中com.google.appengine.api.urlfetch.HTTPResponse.getResponseCode方法的典型用法代码示例。如果您正苦于以下问题:Java HTTPResponse.getResponseCode方法的具体用法?Java HTTPResponse.getResponseCode怎么用?Java HTTPResponse.getResponseCode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.appengine.api.urlfetch.HTTPResponse
的用法示例。
在下文中一共展示了HTTPResponse.getResponseCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doGet
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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.
}
示例2: refreshNeeded
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
@Override public boolean refreshNeeded(HTTPResponse resp) throws IOException {
if (resp.getResponseCode() == 401) {
log.warning("Response code 401: " + resp);
return true;
}
if (!EXPECTED_CONTENT_TYPE.equals(
OAuthedFetchService.getSingleHeader(resp, "Content-Type"))) {
return false;
}
JSONObject result = parseJsonResponseBody(resp);
try {
if (result.has("error")) {
JSONObject error = result.getJSONObject("error");
if (error.has("code") && error.getInt("code") == 401) {
log.warning("Looks like a 401: " + result + ", " + resp);
return true;
} else {
return false;
}
} else {
return false;
}
} catch (JSONException e) {
throw new RuntimeException("JSONException parsing response: " + result, e);
}
}
示例3: uploadCsvToLordn
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
/**
* Upload LORDN file to MarksDB.
*
* <p>Idempotency: If the exact same LORDN report is uploaded twice, the MarksDB server will
* return the same confirmation number.
*
* @see <a href="http://tools.ietf.org/html/draft-lozano-tmch-func-spec-08#section-6.3">
* TMCH functional specifications - LORDN File</a>
*/
private void uploadCsvToLordn(String urlPath, String csvData) throws IOException {
String url = tmchMarksdbUrl + urlPath;
logger.infofmt("LORDN upload task %s: Sending to URL: %s ; data: %s",
actionLogId, url, csvData);
HTTPRequest req = new HTTPRequest(new URL(url), POST, validateCertificate().setDeadline(60d));
lordnRequestInitializer.initialize(req, tld);
setPayloadMultipart(req, "file", "claims.csv", CSV_UTF_8, csvData);
HTTPResponse rsp = fetchService.fetch(req);
logger.infofmt("LORDN upload task %s response: HTTP response code %d, response data: %s",
actionLogId, rsp.getResponseCode(), rsp.getContent());
if (rsp.getResponseCode() != SC_ACCEPTED) {
throw new UrlFetchException(
String.format("LORDN upload task %s error: Failed to upload LORDN claims to MarksDB",
actionLogId),
req, rsp);
}
Optional<String> location = getHeaderFirst(rsp, LOCATION);
if (!location.isPresent()) {
throw new UrlFetchException(
String.format("LORDN upload task %s error: MarksDB failed to provide a Location header",
actionLogId),
req, rsp);
}
getQueue(NordnVerifyAction.QUEUE).add(makeVerifyTask(new URL(location.get()), csvData));
}
示例4: _doRequest
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
/**
* Hace la llamada a URLFetch de google
* @throws IOException
*/
private void _doRequest() throws IOException {
URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
fetchOptions.doNotValidateCertificate();
fetchOptions.setDeadline(_conxTimeOut);
HTTPRequest request = new HTTPRequest(this.getURL(),_requestMethod,
fetchOptions);
if (_requestOS != null) {
byte[] bytes = _requestOS.toByteArray();
if (bytes != null && bytes.length > 0) {
request.setPayload(bytes);
}
}
HTTPResponse httpResponse = urlFetchService.fetch(request);
_responseCode = httpResponse.getResponseCode();
_responseIS = new ByteArrayInputStream(httpResponse.getContent());
}
示例5: trackEventToGoogleAnalytics
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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
示例6: doGet
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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");
}
}
示例7: beginObjectCreation
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
@Override
public RawGcsCreationToken beginObjectCreation(
GcsFilename filename, GcsFileOptions options, long timeoutMillis) throws IOException {
HTTPRequest req = makeRequest(filename, null, POST, timeoutMillis);
req.setHeader(RESUMABLE_HEADER);
addOptionsHeaders(req, options);
HTTPResponse resp;
try {
resp = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(new HTTPRequestInfo(req), e);
}
if (resp.getResponseCode() == 201) {
String location = URLFetchUtils.getSingleHeader(resp, LOCATION);
String queryString = new URL(location).getQuery();
Preconditions.checkState(
queryString != null, LOCATION + " header," + location + ", witout a query string");
Map<String, String> params = Splitter.on('&').withKeyValueSeparator('=').split(queryString);
Preconditions.checkState(params.containsKey(UPLOAD_ID),
LOCATION + " header," + location + ", has a query string without " + UPLOAD_ID);
return new GcsRestCreationToken(filename, params.get(UPLOAD_ID), 0);
} else {
throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
}
}
示例8: handlePutResponse
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
/**
* Given a HTTPResponce, process it, throwing an error if needed and return a Token for the next
* request.
*/
GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,
final boolean isFinalChunk,
final int length,
final HTTPRequestInfo reqInfo,
HTTPResponse resp) throws Error, IOException {
switch (resp.getResponseCode()) {
case 200:
if (!isFinalChunk) {
throw new RuntimeException("Unexpected response code 200 on non-final chunk. Request: \n"
+ URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
} else {
return null;
}
case 308:
if (isFinalChunk) {
throw new RuntimeException("Unexpected response code 308 on final chunk: "
+ URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
} else {
return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);
}
default:
throw HttpErrorHandler.error(resp.getResponseCode(),
URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
}
}
示例9: deleteObject
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
/** True if deleted, false if not found. */
@Override
public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {
HTTPRequest req = makeRequest(filename, null, DELETE, timeoutMillis);
HTTPResponse resp;
try {
resp = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(new HTTPRequestInfo(req), e);
}
switch (resp.getResponseCode()) {
case 204:
return true;
case 404:
return false;
default:
throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
}
}
示例10: getObjectMetadata
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
@Override
public GcsFileMetadata getObjectMetadata(GcsFilename filename, long timeoutMillis)
throws IOException {
HTTPRequest req = makeRequest(filename, null, HEAD, timeoutMillis);
HTTPResponse resp;
try {
resp = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(new HTTPRequestInfo(req), e);
}
int responseCode = resp.getResponseCode();
if (responseCode == 404) {
return null;
}
if (responseCode != 200) {
throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
}
return getMetadataFromResponse(
filename, resp, getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH));
}
示例11: composeObject
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的package包/类
@Override
public void composeObject(Iterable<String> source, GcsFilename dest, long timeoutMillis)
throws IOException {
StringBuilder xmlContent = new StringBuilder(Iterables.size(source) * 50);
Escaper escaper = XmlEscapers.xmlContentEscaper();
xmlContent.append("<ComposeRequest>");
for (String srcFileName : source) {
xmlContent.append("<Component><Name>")
.append(escaper.escape(srcFileName))
.append("</Name></Component>");
}
xmlContent.append("</ComposeRequest>");
HTTPRequest req = makeRequest(
dest, COMPOSE_QUERY_STRINGS, PUT, timeoutMillis, xmlContent.toString().getBytes(UTF_8));
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);
}
}
示例12: copyObject
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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);
}
}
示例13: createInstance
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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
示例14: checkDiskOrInstance
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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
示例15: deleteInstance
import com.google.appengine.api.urlfetch.HTTPResponse; //导入方法依赖的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