use of com.google.api.client.http.HttpRequest in project google-cloud-java by GoogleCloudPlatform.
the class HttpTranslateRpc method detect.
@Override
public List<List<DetectionsResourceItems>> detect(List<String> texts) {
try {
Map<String, ?> content = ImmutableMap.of("q", texts);
HttpRequest httpRequest = translate.getRequestFactory().buildPostRequest(buildTargetUrl("detect"), new JsonHttpContent(translate.getJsonFactory(), content)).setParser(translate.getObjectParser());
List<List<DetectionsResourceItems>> detections = httpRequest.execute().parseAs(DetectionsListResponse.class).getDetections();
// translate.detections().list(texts).setKey(options.getApiKey()).execute().getDetections();
return detections != null ? detections : ImmutableList.<List<DetectionsResourceItems>>of();
} catch (IOException ex) {
throw translate(ex);
}
}
use of com.google.api.client.http.HttpRequest in project ddf by codice.
the class PaosInInterceptor method getHttpResponse.
HttpResponseWrapper getHttpResponse(String responseConsumerURL, String soapResponse, Message message) throws IOException {
//This used to use the ApacheHttpTransport which appeared to not work with 2 way TLS auth but this one does
HttpTransport httpTransport = new NetHttpTransport();
HttpContent httpContent = new InputStreamContent(TEXT_XML, new ByteArrayInputStream(soapResponse.getBytes("UTF-8")));
//this handles redirects for us
((InputStreamContent) httpContent).setRetrySupported(true);
HttpRequest httpRequest = httpTransport.createRequestFactory().buildPostRequest(new GenericUrl(responseConsumerURL), httpContent);
HttpUnsuccessfulResponseHandler httpUnsuccessfulResponseHandler = (request, response, supportsRetry) -> {
String redirectLocation = response.getHeaders().getLocation();
if (request.getFollowRedirects() && HttpStatusCodes.isRedirect(response.getStatusCode()) && redirectLocation != null) {
String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
HttpContent content = null;
if (!isRedirectable(method)) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
message.setContent(OutputStream.class, byteArrayOutputStream);
BodyWriter bodyWriter = new BodyWriter();
bodyWriter.handleMessage(message);
content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE), new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
}
// resolve the redirect location relative to the current location
request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation)));
request.setRequestMethod(method);
request.setContent(content);
// remove Authorization and If-* headers
request.getHeaders().setAuthorization((String) null);
request.getHeaders().setIfMatch(null);
request.getHeaders().setIfNoneMatch(null);
request.getHeaders().setIfModifiedSince(null);
request.getHeaders().setIfUnmodifiedSince(null);
request.getHeaders().setIfRange(null);
request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0));
return true;
}
return false;
};
httpRequest.setUnsuccessfulResponseHandler(httpUnsuccessfulResponseHandler);
httpRequest.getHeaders().put(SOAP_ACTION, HTTP_WWW_OASIS_OPEN_ORG_COMMITTEES_SECURITY);
//has 20 second timeout by default
HttpResponse httpResponse = httpRequest.execute();
HttpResponseWrapper httpResponseWrapper = new HttpResponseWrapper();
httpResponseWrapper.statusCode = httpResponse.getStatusCode();
httpResponseWrapper.content = httpResponse.getContent();
return httpResponseWrapper;
}
use of com.google.api.client.http.HttpRequest in project gradle by gradle.
the class RetryHttpInitializerWrapper method initialize.
@Override
public void initialize(HttpRequest request) {
// Turn off request logging, this can end up logging OAUTH
// tokens which should not ever be in a build log
final boolean loggingEnabled = false;
request.setLoggingEnabled(loggingEnabled);
request.setCurlLoggingEnabled(loggingEnabled);
disableHttpTransportLogging();
request.setReadTimeout((int) DEFAULT_READ_TIMEOUT_MILLIS);
final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setSleeper(sleeper);
final Credential credential = credentialSupplier.get();
request.setInterceptor(credential);
request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
// Turn off request logging unless debug mode is enabled
request.setLoggingEnabled(loggingEnabled);
request.setCurlLoggingEnabled(loggingEnabled);
if (credential.handleResponse(request, response, supportsRetry)) {
// something specific to authentication, and no backoff is desired.
return true;
} else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
// Otherwise, we defer to the judgement of our internal backoff handler.
LOG.info("Retrying " + request.getUrl().toString());
return true;
} else {
return false;
}
}
});
request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()).setSleeper(sleeper));
}
use of com.google.api.client.http.HttpRequest in project AndroidSDK-RecipeBook by gabu.
the class EditActivity method onSaveButtonClick.
public void onSaveButtonClick(View view) {
// GoogleTransportからPUTリクエストを生成
HttpRequest request = mTransport.buildPutRequest();
// URLを生成して
String url = GOOGLE_DOCS_API_URL + "default/media/document%3A" + mDocId;
// URLをセット
request.setUrl(url);
// EditTextの内容でPlainTextContentを作って
PlainTextContent content = new PlainTextContent(mEditText.getText().toString());
// HttpRequestにPlainTextContentをセット
request.content = content;
// HttpRequestのヘッダーのifMatchに"*"をセット
request.headers.ifMatch = "*";
try {
// HTTPリクエストを実行!
request.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
use of com.google.api.client.http.HttpRequest in project AndroidSDK-RecipeBook by gabu.
the class Recipe098 method onCreate.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// GoogleTransportを作る
mTransport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) mTransport.defaultHeaders;
// "[company-id]-[app-name]-[app-version]"という形式で
// アプリケーション名をセット
headers.setApplicationName("gabu-recipe-98");
// バージョンをセット
headers.gdataVersion = "3";
// AtomParserを作る
AtomParser parser = new AtomParser();
// GoogleDocumentsListのネームスペースをセット
parser.namespaceDictionary = Namespace.DICTIONARY;
// GoogleTransportにAtomParserをセット
mTransport.addParser(parser);
// HttpTransportにApacheHttpTransportのインスタンスをセット
// これをやっておかないとExceptionが発生します。
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
// AccountManagerを取得
AccountManager manager = AccountManager.get(this);
// Googleアカウントの一覧を取得
Account[] accounts = manager.getAccountsByType("com.google");
// サンプルなので暫定的に1つ目を取得
Account acount = accounts[0];
// 認証のためのauth tokenを取得
AccountManagerFuture<Bundle> f = manager.getAuthToken(acount, DOCS_AUTH_TOKEN_TYPE, null, this, null, null);
try {
Bundle b = f.getResult();
mAuthToken = b.getString(AccountManager.KEY_AUTHTOKEN);
// Log.d(TAG, "authToken=" + mAuthToken);
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// GoogleTransportにauth tokenをセット
// これで認証ヘッダを自動的に付けてくれます。
((GoogleHeaders) mTransport.defaultHeaders).setGoogleLogin(mAuthToken);
// Googleドキュメントの一覧を取得するURLを作成
String url = GOOGLE_DOCS_API_URL + "default/private/full/-/document";
// GoogleTransportからGETリクエストを生成
HttpRequest request = mTransport.buildGetRequest();
// URLをセット
request.setUrl(url);
try {
// HTTPリクエストを実行してレスポンスをパース
DocumentListFeed feed = request.execute().parseAs(DocumentListFeed.class);
// DocsAdapterを生成
DocsAdapter adapter = new DocsAdapter(getApplicationContext(), 0, feed.entries);
// ListViewにDocsAdapterをセット
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(mOnItemClickListener);
} catch (IOException e) {
handleException(e);
}
}
Aggregations