本文整理汇总了Java中com.google.appengine.api.urlfetch.HTTPResponse类的典型用法代码示例。如果您正苦于以下问题:Java HTTPResponse类的具体用法?Java HTTPResponse怎么用?Java HTTPResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HTTPResponse类属于com.google.appengine.api.urlfetch包,在下文中一共展示了HTTPResponse类的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: parseJsonResponseBody
import com.google.appengine.api.urlfetch.HTTPResponse; //导入依赖的package包/类
private JSONObject parseJsonResponseBody(HTTPResponse resp) throws IOException {
// The response looks like this:
// [{"id":"op_id", "data":X}]
// We return the single item in this array.
String body = OAuthedFetchService.getUtf8ResponseBody(resp, EXPECTED_CONTENT_TYPE);
try {
JSONArray items = new JSONArray(body);
if (items.length() != 1) {
throw new RuntimeException("Unexpected length: " + items.length() + ": " + items);
}
JSONObject item = items.getJSONObject(0);
if (!OP_ID.equals(item.getString("id"))) {
throw new RuntimeException("Unexpected id: " + item);
}
return item;
} catch (JSONException e) {
throw new RuntimeException("JSONException parsing response: " + body, e);
}
}
示例4: fetch1
import com.google.appengine.api.urlfetch.HTTPResponse; //导入依赖的package包/类
private HTTPResponse fetch1(HTTPRequest req, TokenRefreshNeededDetector refreshNeeded,
boolean tokenJustRefreshed) throws IOException {
log.info("Sending request (token just refreshed: " + tokenJustRefreshed + "): "
+ describeRequest(req));
helper.authorize(req);
//log.info("req after authorizing: " + describeRequest(req));
HTTPResponse resp = fetch.fetch(req);
log.info("response: " + describeResponse(resp, false));
if (refreshNeeded.refreshNeeded(resp)) {
if (tokenJustRefreshed) {
throw new NeedNewOAuthTokenException("Token just refreshed, still no good: "
+ describeResponse(resp, true));
} else {
helper.refreshToken();
return fetch1(req, refreshNeeded, true);
}
} else {
return resp;
}
}
示例5: proxy
import com.google.appengine.api.urlfetch.HTTPResponse; //导入依赖的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);
}
示例6: 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));
}
示例7: _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());
}
示例8: getCharset
import com.google.appengine.api.urlfetch.HTTPResponse; //导入依赖的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;
}
示例9: 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
示例10: 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");
}
}
示例11: 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);
}
}
示例12: 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));
}
}
示例13: putAsync
import com.google.appengine.api.urlfetch.HTTPResponse; //导入依赖的package包/类
/**
* Same as {@link #put} but is runs asynchronously and returns a future. In the event of an error
* the exception out of the future will be an ExecutionException with the cause set to the same
* exception that would have been thrown by put.
*/
private Future<RawGcsCreationToken> putAsync(final GcsRestCreationToken token,
ByteBuffer chunk, final boolean isFinalChunk, long timeoutMillis) {
final int length = chunk.remaining();
HTTPRequest request = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);
final HTTPRequestInfo info = new HTTPRequestInfo(request);
return new FutureWrapper<HTTPResponse, RawGcsCreationToken>(urlfetch.fetchAsync(request)) {
@Override
protected Throwable convertException(Throwable e) {
return OauthRawGcsService.convertException(info, e);
}
@Override
protected GcsRestCreationToken wrap(HTTPResponse resp) throws Exception {
return handlePutResponse(token, isFinalChunk, length, info, resp);
}
};
}
示例14: 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);
}
}
示例15: 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));
}