Search in sources :

Example 31 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project feign by OpenFeign.

the class GoogleHttpClient method convertRequest.

private final HttpRequest convertRequest(final Request inputRequest, final Request.Options options) throws IOException {
    // Setup the request body
    HttpContent content = null;
    if (inputRequest.length() > 0) {
        final Collection<String> contentTypeValues = inputRequest.headers().get("Content-Type");
        String contentType = null;
        if (contentTypeValues != null && contentTypeValues.size() > 0) {
            contentType = contentTypeValues.iterator().next();
        } else {
            contentType = "application/octet-stream";
        }
        content = new ByteArrayContent(contentType, inputRequest.body());
    }
    // Build the request
    final HttpRequest request = requestFactory.buildRequest(inputRequest.httpMethod().name(), new GenericUrl(inputRequest.url()), content);
    // Setup headers
    final HttpHeaders headers = new HttpHeaders();
    for (final Map.Entry<String, Collection<String>> header : inputRequest.headers().entrySet()) {
        headers.set(header.getKey(), header.getValue());
    }
    // Some servers don't do well with no Accept header
    if (inputRequest.headers().get("Accept") == null) {
        headers.setAccept("*/*");
    }
    request.setHeaders(headers);
    // Setup request options
    request.setReadTimeout(options.readTimeoutMillis()).setConnectTimeout(options.connectTimeoutMillis()).setFollowRedirects(options.isFollowRedirects()).setThrowExceptionOnExecuteError(false);
    return request;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Collection(java.util.Collection) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) HashMap(java.util.HashMap) Map(java.util.Map) HttpContent(com.google.api.client.http.HttpContent)

Example 32 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project scout.rt by eclipse.

the class HttpServiceTunnel method executeRequest.

/**
 * Execute a {@link ServiceTunnelRequest}, returns the plain {@link HttpResponse} - (executed and) ready to be
 * processed to create a {@link ServiceTunnelResponse}.
 *
 * @param call
 *          the original call
 * @param callData
 *          the data created by the {@link IServiceTunnelContentHandler} used by this tunnel Create url connection and
 *          write post data (if required)
 * @throws IOException
 *           override this method to customize the creation of the {@link HttpResponse} see
 *           {@link #addCustomHeaders(HttpRequest, ServiceTunnelRequest, byte[])}
 */
protected HttpResponse executeRequest(ServiceTunnelRequest call, byte[] callData) throws IOException {
    // fast check of wrong URL's for this tunnel
    if (!"http".equalsIgnoreCase(getServerUrl().getProtocol()) && !"https".equalsIgnoreCase(getServerUrl().getProtocol())) {
        throw new IOException("URL '" + getServerUrl().toString() + "' is not supported by this tunnel ('" + getClass().getName() + "').");
    }
    if (!isActive()) {
        String key = BEANS.get(ServiceTunnelTargetUrlProperty.class).getKey();
        throw new IllegalArgumentException("No target URL configured. Please specify a target URL in the config.properties using property '" + key + "'.");
    }
    HttpRequestFactory requestFactory = getHttpTransportManager().getHttpRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(getGenericUrl(), new ByteArrayContent(null, callData));
    HttpHeaders headers = request.getHeaders();
    headers.setCacheControl("no-cache");
    headers.setContentType("text/xml");
    headers.put("Pragma", "no-cache");
    addCustomHeaders(request, call, callData);
    return request.execute();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) ServiceTunnelTargetUrlProperty(org.eclipse.scout.rt.shared.SharedConfigProperties.ServiceTunnelTargetUrlProperty) IOException(java.io.IOException) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 33 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project googleads-java-lib by googleads.

the class AxisBatchJobUploadBodyProvider method getHttpContent.

@Override
public ByteArrayContent getHttpContent(BatchJobMutateRequestInterface request, boolean isFirstRequest, boolean isLastRequest) throws BatchJobException {
    Preconditions.checkNotNull(request, "Null request");
    StringWriter writer = new StringWriter();
    SerializationContext context = new SerializationContext(writer) {

        /**
         * Override the serialize method called by the Axis serializer and force it to
         * pass {@code includeNull = false}.
         */
        @SuppressWarnings("rawtypes")
        @Override
        public void serialize(QName elemQName, Attributes attributes, Object value, QName xmlType, Class javaType) throws IOException {
            super.serialize(elemQName, attributes, value, xmlType, javaType, false, null);
        }
    };
    context.setSendDecl(false);
    context.setPretty(true);
    // Pre-register namespaces using the *sorted* list of namespaces. This ensures that
    // when performing an incremental upload, the same namespace prefix will be used
    // for each namespace URI across all uploads.
    int namespaceIndex = 0;
    for (String namespaceUri : namespaceUris) {
        context.registerPrefixForURI(String.format("ns%d", namespaceIndex++), namespaceUri);
    }
    AxisSerializer serializer = new AxisSerializer();
    serializer.serialize(request, context);
    return new ByteArrayContent("application/xml", writer.toString().getBytes(UTF_8));
}
Also used : SerializationContext(org.apache.axis.encoding.SerializationContext) StringWriter(java.io.StringWriter) QName(javax.xml.namespace.QName) Attributes(org.xml.sax.Attributes) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 34 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project googleads-java-lib by googleads.

the class BatchJobUploadBodyProviderTest method testValidOperations.

@Test
public void testValidOperations() throws BatchJobException, IOException, SAXException {
    RequestT request = createMutateRequest();
    addBudgetOperation(request, -1L, "Test budget", 50000000L, "STANDARD");
    addCampaignOperation(request, -2L, "Test campaign #1", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
    addCampaignOperation(request, -3L, "Test campaign #2", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
    addCampaignNegativeKeywordOperation(request, -2L, "venus", "BROAD");
    addCampaignNegativeKeywordOperation(request, -3L, "venus", "BROAD");
    ByteArrayContent httpContent = request.createBatchJobUploadBodyProvider().getHttpContent(request, true, true);
    String actualRequestXml = Streams.readAll(httpContent.getInputStream(), Charset.forName(UTF_8));
    actualRequestXml = SoapRequestXmlProvider.normalizeXmlForComparison(actualRequestXml, getApiVersion());
    String expectedRequestXml = SoapRequestXmlProvider.getTestBatchUploadRequest(getApiVersion());
    // Perform an XML diff using the custom difference listener that properly handles namespaces
    // and attributes.
    Diff diff = DiffBuilder.compare(expectedRequestXml).normalizeWhitespace().withDifferenceEvaluator(new CustomDifferenceEvaluator()).withTest(actualRequestXml).checkForSimilar().build();
    assertFalse("XML similar " + diff, diff.hasDifferences());
}
Also used : CustomDifferenceEvaluator(com.google.api.ads.common.lib.soap.testing.CustomDifferenceEvaluator) Diff(org.xmlunit.diff.Diff) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Test(org.junit.Test)

Example 35 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project googleads-java-lib by googleads.

the class MockHttpServerTest method testUrlMismatch_verifyDisabled.

/**
 * Tests behavior when URL validation is disabled.
 */
@Test
public void testUrlMismatch_verifyDisabled() throws IOException {
    MockResponse mockResponse = new MockResponse("test response");
    mockResponse.setValidateUrlMatches(false);
    HttpRequest request = mockHttpServer.getHttpTransport().createRequestFactory().buildGetRequest(new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url"));
    request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8)));
    HttpHeaders headers = new HttpHeaders();
    headers.set("one", "1");
    headers.set("two", "2");
    request.setHeaders(headers);
    mockHttpServer.setMockResponse(mockResponse);
    HttpResponse response = request.execute();
    ActualResponse actualResponse = mockHttpServer.getLastResponse();
    assertEquals("Incorrect response code", 200, response.getStatusCode());
    assertEquals("Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0));
    assertEquals("Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Test(org.junit.Test)

Aggregations

ByteArrayContent (com.google.api.client.http.ByteArrayContent)43 GenericUrl (com.google.api.client.http.GenericUrl)24 HttpRequest (com.google.api.client.http.HttpRequest)17 IOException (java.io.IOException)12 Test (org.junit.Test)12 HttpResponse (com.google.api.client.http.HttpResponse)10 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)7 HttpContent (com.google.api.client.http.HttpContent)6 HttpHeaders (com.google.api.client.http.HttpHeaders)6 Gson (com.google.gson.Gson)6 MockResponse (com.google.api.ads.common.lib.testing.MockResponse)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)4 File (com.google.api.services.drive.model.File)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Credential (com.google.api.client.auth.oauth2.Credential)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 HttpResponseException (com.google.api.client.http.HttpResponseException)3 InputStreamContent (com.google.api.client.http.InputStreamContent)3 AbstractInputStreamContent (com.google.api.client.http.AbstractInputStreamContent)2