本文整理匯總了Java中com.google.api.client.http.HttpRequest.setHeaders方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpRequest.setHeaders方法的具體用法?Java HttpRequest.setHeaders怎麽用?Java HttpRequest.setHeaders使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.api.client.http.HttpRequest
的用法示例。
在下文中一共展示了HttpRequest.setHeaders方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: sendPostMultipart
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public static int sendPostMultipart(String urlString, Map<String, String> parameters)
throws IOException {
MultipartContent postBody = new MultipartContent()
.setMediaType(new HttpMediaType("multipart/form-data"));
postBody.setBoundary(MULTIPART_BOUNDARY);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
HttpContent partContent = ByteArrayContent.fromString( // uses UTF-8 internally
null /* part Content-Type */, entry.getValue());
HttpHeaders partHeaders = new HttpHeaders()
.set("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"");
postBody.addPart(new MultipartContent.Part(partHeaders, partContent));
}
GenericUrl url = new GenericUrl(new URL(urlString));
HttpRequest request = transport.createRequestFactory().buildPostRequest(url, postBody);
request.setHeaders(new HttpHeaders().setUserAgent(CloudToolsInfo.USER_AGENT));
request.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS);
request.setReadTimeout(DEFAULT_READ_TIMEOUT_MS);
HttpResponse response = request.execute();
return response.getStatusCode();
}
示例2: getUsersSince
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public List<User> getUsersSince(int since)
throws IOException
{
HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(API_ENDPOINT + "/users?since=" + since));
HttpHeaders headers = new HttpHeaders();
headers.setAuthorization("bearer " + tokenFactory.getToken());
request.setHeaders(headers);
HttpResponse response = executeWithRetry(request);
// TODO: Handle error status code
List<JsonObject> userObjects = Json.createReader(new StringReader(response.parseAsString())).readArray().getValuesAs(JsonObject.class);
List<User> users = new ArrayList<>();
for (JsonObject userObject : userObjects) {
User user = new User(userObject.getInt("id"), userObject.getString("type"));
user.setLogin(userObject.getString("login"));
user.setAvatarUrl(userObject.getString("avatar_url"));
users.add(user);
}
return users;
}
示例3: graphql
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
private JsonObject graphql(String query)
throws IOException
{
String payload = Json.createObjectBuilder()
.add("query", query)
.add("variables", "{}")
.build().toString();
HttpRequest request = requestFactory.buildPostRequest(
new GenericUrl(GRAPHQL_ENDPOINT),
ByteArrayContent.fromString("application/json", payload));
HttpHeaders headers = new HttpHeaders();
headers.setAuthorization("bearer " + tokenFactory.getToken());
request.setHeaders(headers);
HttpResponse response = executeWithRetry(request);
// TODO: Handle error status code
JsonObject responseObject = Json.createReader(new StringReader(response.parseAsString())).readObject();
if (responseObject.containsKey("errors")) {
LOG.debug("errors with query:\n" + query);
LOG.debug("response:\n" + responseObject.toString());
}
return responseObject;
}
示例4: executeInsertPhotoEntry
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public PhotoEntry executeInsertPhotoEntry(
PicasaUrl albumFeedUrl, InputStreamContent content, String fileName) throws IOException {
HttpRequest request = getRequestFactory().buildPostRequest(albumFeedUrl, content);
HttpHeaders headers = new HttpHeaders();
Atom.setSlugHeader(headers, fileName);
request.setHeaders(headers);
return execute(request).parseAs(PhotoEntry.class);
}
示例5: build
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
public Client build() throws GeneralSecurityException, IOException {
HttpTransport h = this.transport;
if (h == null) {
h = GoogleNetHttpTransport.newTrustedTransport();
}
GoogleCredential c = GoogleCredential.getApplicationDefault(transport, new JacksonFactory());
if (c.createScopedRequired()) {
c = c.createScoped(ServiceControlScopes.all());
}
ThreadFactory f = this.factory;
if (f == null) {
f = new ThreadFactoryBuilder().build();
}
CheckAggregationOptions o = this.checkOptions;
if (o == null) {
o = new CheckAggregationOptions();
}
ReportAggregationOptions r = this.reportOptions;
if (r == null) {
r = new ReportAggregationOptions();
}
QuotaAggregationOptions q = this.quotaOptions;
if (q == null) {
q = new QuotaAggregationOptions();
}
final GoogleCredential nestedInitializer = c;
HttpRequestInitializer addUserAgent = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
HttpHeaders hdr = new HttpHeaders().setUserAgent(KnownLabels.USER_AGENT);
request.setHeaders(hdr);
nestedInitializer.initialize(request);
}
};
return new Client(serviceName, o, r, q,
new ServiceControl.Builder(h, c)
.setHttpRequestInitializer(addUserAgent)
.setApplicationName(CLIENT_APPLICATION_NAME)
.build(),
f, schedulerFactory, statsLogFrequency, ticker);
}
示例6: execute
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
* Executes the HTTP request for a temporary or long-lived token.
*
* @throws IOException
*/
public final HttpResponse execute() throws IOException {
ApacheHttpTransport.Builder builder = new ApacheHttpTransport.Builder();
if(this.proxyEnabled) {
builder.setProxy(this.proxy);
}
transport = builder.build();
if(usePost && body != null){
requestBody = ByteArrayContent.fromString(null, body);
}
HttpHeaders headers = new HttpHeaders();
headers.setUserAgent(config.getUserAgent());
headers.setAccept(accept != null ? accept : config.getAccept());
headers.setContentType(contentType == null ? "application/xml" : contentType);
if(ifModifiedSince != null) {
//System.out.println("Set Header " + this.ifModifiedSince);
headers.setIfModifiedSince(this.ifModifiedSince);
}
HttpRequestFactory requestFactory = transport.createRequestFactory();
HttpRequest request;
HttpResponse response = null;
request = requestFactory.buildRequest(this.httpMethod, Url, requestBody);
request.setConnectTimeout(connectTimeout);
request.setReadTimeout(readTimeout);
request.setHeaders(headers);
createParameters().intercept(request);
response = request.execute();
response.setContentLoggingLimit(0);
return response;
}
示例7: send
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */
public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException {
validateReportFilename(reportFilename);
GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename));
HttpRequest request =
httpTransport
.createRequestFactory()
.buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes));
HttpHeaders headers = request.getHeaders();
headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password);
headers.setContentType(CSV_UTF_8.toString());
request.setHeaders(headers);
request.setFollowRedirects(false);
HttpResponse response = null;
logger.infofmt(
"Sending report to %s with content length %s",
uploadUrl.toString(), request.getContent().getLength());
boolean success = true;
try {
response = request.execute();
byte[] content;
try {
content = ByteStreams.toByteArray(response.getContent());
} finally {
response.getContent().close();
}
logger.infofmt(
"Received response code %s with content %s",
response.getStatusCode(), new String(content, UTF_8));
XjcIirdeaResult result = parseResult(content);
if (result.getCode().getValue() != 1000) {
success = false;
logger.warningfmt(
"PUT rejected, status code %s:\n%s\n%s",
result.getCode(),
result.getMsg(),
result.getDescription());
}
} finally {
if (response != null) {
response.disconnect();
} else {
success = false;
logger.warningfmt(
"Received null response from ICANN server at %s", uploadUrl.toString());
}
}
return success;
}
示例8: labelDataset
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
* Add or modify a label on a dataset.
*
* <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
* documentation</a>.
*/
public static void labelDataset(
String projectId, String datasetId, String labelKey, String labelValue) throws IOException {
// Authenticate requests using Google Application Default credentials.
GoogleCredential credential = GoogleCredential.getApplicationDefault();
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
// Get a new access token.
// Note that access tokens have an expiration. You can reuse a token rather than requesting a
// new one if it is not yet expired.
credential.refreshToken();
String accessToken = credential.getAccessToken();
// Set the content of the request.
Dataset dataset = new Dataset();
dataset.addLabel(labelKey, labelValue);
HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);
// Send the request to the BigQuery API.
String urlFormat =
"https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
+ "?fields=labels&access_token=%s";
GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken));
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
HttpRequest request = requestFactory.buildPostRequest(url, content);
request.setParser(JSON_FACTORY.createJsonObjectParser());
// Workaround for transports which do not support PATCH requests.
// See: http://stackoverflow.com/a/32503192/101923
request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
HttpResponse response = request.execute();
// Check for errors.
if (response.getStatusCode() != 200) {
throw new RuntimeException(response.getStatusMessage());
}
Dataset responseDataset = response.parseAs(Dataset.class);
System.out.printf(
"Updated label \"%s\" with value \"%s\"\n",
labelKey, responseDataset.getLabels().get(labelKey));
}
示例9: labelTable
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/**
* Add or modify a label on a table.
*
* <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
* documentation</a>.
*/
public static void labelTable(
String projectId,
String datasetId,
String tableId,
String labelKey,
String labelValue)
throws IOException {
// Authenticate requests using Google Application Default credentials.
GoogleCredential credential = GoogleCredential.getApplicationDefault();
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
// Get a new access token.
// Note that access tokens have an expiration. You can reuse a token rather than requesting a
// new one if it is not yet expired.
credential.refreshToken();
String accessToken = credential.getAccessToken();
// Set the content of the request.
Table table = new Table();
table.addLabel(labelKey, labelValue);
HttpContent content = new JsonHttpContent(JSON_FACTORY, table);
// Send the request to the BigQuery API.
String urlFormat =
"https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
+ "?fields=labels&access_token=%s";
GenericUrl url =
new GenericUrl(String.format(urlFormat, projectId, datasetId, tableId, accessToken));
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
HttpRequest request = requestFactory.buildPostRequest(url, content);
request.setParser(JSON_FACTORY.createJsonObjectParser());
// Workaround for transports which do not support PATCH requests.
// See: http://stackoverflow.com/a/32503192/101923
request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
HttpResponse response = request.execute();
// Check for errors.
if (response.getStatusCode() != 200) {
throw new RuntimeException(response.getStatusMessage());
}
Table responseTable = response.parseAs(Table.class);
System.out.printf(
"Updated label \"%s\" with value \"%s\"\n",
labelKey, responseTable.getLabels().get(labelKey));
}
示例10: getConfig
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void getConfig(String urlPath, String token, String projectId,
String cloudRegion, String registryId, String deviceId, String version)
throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
// Build the resource path of the device that is going to be authenticated.
String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
projectId, cloudRegion, registryId, deviceId);
urlPath = urlPath + devicePath + "/config?local_version=" + version;
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
HttpHeaders heads = new HttpHeaders();
heads.setAuthorization(String.format("Bearer %s", token));
heads.setContentType("application/json; charset=UTF-8");
heads.setCacheControl("no-cache");
req.setHeaders(heads);
ExponentialBackOff backoff = new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
HttpResponse res = req.execute();
System.out.println(res.getStatusCode());
System.out.println(res.getStatusMessage());
InputStream in = res.getContent();
System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
示例11: publishMessage
import com.google.api.client.http.HttpRequest; //導入方法依賴的package包/類
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
public static void publishMessage(String payload, String urlPath, String messageType,
String token, String projectId, String cloudRegion, String registryId, String deviceId)
throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
// Build the resource path of the device that is going to be authenticated.
String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
projectId, cloudRegion, registryId, deviceId);
String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";
// Data sent through the wire has to be base64 encoded.
Base64.Encoder encoder = Base64.getEncoder();
String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));
urlPath = urlPath + devicePath + ":" + urlSuffix;
final HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpHeaders heads = new HttpHeaders();
heads.setAuthorization(String.format("Bearer %s", token));
heads.setContentType("application/json; charset=UTF-8");
heads.setCacheControl("no-cache");
// Add post data. The data sent depends on whether we're updating state or publishing events.
JSONObject data = new JSONObject();
if (messageType.equals("event")) {
data.put("binary_data", encPayload);
} else {
JSONObject state = new JSONObject();
state.put("binary_data", encPayload);
data.put("state", state);
}
ByteArrayContent content = new ByteArrayContent(
"application/json", data.toString().getBytes("UTF-8"));
final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
req.setHeaders(heads);
req.setContent(content);
req.setRequestMethod("POST");
ExponentialBackOff backoff = new ExponentialBackOff.Builder()
.setInitialIntervalMillis(500)
.setMaxElapsedTimeMillis(900000)
.setMaxIntervalMillis(6000)
.setMultiplier(1.5)
.setRandomizationFactor(0.5)
.build();
req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
HttpResponse res = req.execute();
System.out.println(res.getStatusCode());
System.out.println(res.getStatusMessage());
}