@Override
  public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    OkHttpClient client = okHttpClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder =
        new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();

    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }

    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus =
        new BasicStatusLine(
            parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(),
            okHttpResponse.message());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();

    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);

      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }

    return response;
  }
Ejemplo n.º 2
0
 private void addHeadersToResponse(BasicHttpResponse response, HttpURLConnection connection) {
   for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
     if (header.getKey() != null) {
       Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
       response.addHeader(h);
     }
   }
 }
Ejemplo n.º 3
0
 @Override
 public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
     throws IOException, AuthFailureError {
   String url = request.getUrl();
   HashMap<String, String> map = new HashMap<String, String>();
   map.putAll(request.getHeaders());
   map.putAll(additionalHeaders);
   if (mUrlRewriter != null) {
     String rewritten = mUrlRewriter.rewriteUrl(url);
     if (rewritten == null) {
       throw new IOException("URL blocked by rewriter: " + url);
     }
     url = rewritten;
   }
   URL parsedUrl = new URL(url);
   HttpURLConnection connection = openConnection(parsedUrl, request);
   for (String headerName : map.keySet()) {
     connection.addRequestProperty(headerName, map.get(headerName));
   }
   setConnectionParametersForRequest(connection, request);
   // Initialize HttpResponse with data from the HttpURLConnection.
   ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
   int responseCode = connection.getResponseCode();
   if (responseCode == -1) {
     // -1 is returned by getResponseCode() if the response code could not be retrieved.
     // Signal to the caller that something was wrong with the connection.
     throw new IOException("Could not retrieve response code from HttpUrlConnection.");
   }
   StatusLine responseStatus =
       new BasicStatusLine(
           protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
   BasicHttpResponse response = new BasicHttpResponse(responseStatus);
   if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
     response.setEntity(entityFromConnection(connection));
   }
   for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
     if (header.getKey() != null) {
       Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
       response.addHeader(h);
     }
   }
   return response;
 }
Ejemplo n.º 4
0
  private static HttpResponse transformResponse(Response response) {
    int code = response.code();
    String message = response.message();
    BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

    ResponseBody body = response.body();
    InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
    httpResponse.setEntity(entity);

    Headers headers = response.headers();
    for (int i = 0; i < headers.size(); i++) {
      String name = headers.name(i);
      String value = headers.value(i);
      httpResponse.addHeader(name, value);
      if ("Content-Type".equalsIgnoreCase(name)) {
        entity.setContentType(value);
      } else if ("Content-Encoding".equalsIgnoreCase(name)) {
        entity.setContentEncoding(value);
      }
    }

    return httpResponse;
  }
Ejemplo n.º 5
0
  public void testHeadersAndPostParams() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse =
        new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
    fakeResponse.setEntity(new StringEntity("foobar"));
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request =
        new Request<String>(Request.Method.GET, "http://foo", null) {

          @Override
          protected Response<String> parseNetworkResponse(NetworkResponse response) {
            return null;
          }

          @Override
          protected void deliverResponse(String response) {}

          @Override
          public Map<String, String> getHeaders() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestheader", "foo");
            return result;
          }

          @Override
          public Map<String, String> getParams() {
            Map<String, String> result = new HashMap<String, String>();
            result.put("requestpost", "foo");
            return result;
          }
        };
    httpNetwork.performRequest(request);
    assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader"));
    assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody()));
  }
Ejemplo n.º 6
0
  private Olingo2BatchResponse parseResponse(
      Edm edm,
      Map<String, String> contentIdLocationMap,
      Olingo2BatchRequest request,
      BatchSingleResponse response)
      throws EntityProviderException, ODataApplicationException {

    // validate HTTP status
    final int statusCode = Integer.parseInt(response.getStatusCode());
    final String statusInfo = response.getStatusInfo();

    final BasicHttpResponse httpResponse =
        new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo));
    final Map<String, String> headers = response.getHeaders();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
      httpResponse.setHeader(entry.getKey(), entry.getValue());
    }

    ByteArrayInputStream content = null;
    try {
      if (response.getBody() != null) {
        final ContentType partContentType =
            receiveWithCharsetParameter(
                ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8);
        final String charset = partContentType.getCharset().toString();

        final String body = response.getBody();
        content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null;

        httpResponse.setEntity(new StringEntity(body, charset));
      }

      AbstractFutureCallback.checkStatus(httpResponse);
    } catch (ODataApplicationException e) {
      return new Olingo2BatchResponse(
          statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
    } catch (UnsupportedEncodingException e) {
      return new Olingo2BatchResponse(
          statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
    }

    // resolve resource path and query params and parse batch part uri
    final String resourcePath = request.getResourcePath();
    final String resolvedResourcePath;
    if (resourcePath.startsWith("$")
        && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) {
      resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap);
    } else {
      final String resourceLocation = response.getHeader(HttpHeaders.LOCATION);
      resolvedResourcePath =
          resourceLocation != null ? resourceLocation.substring(serviceUri.length()) : resourcePath;
    }
    final Map<String, String> resolvedQueryParams =
        request instanceof Olingo2BatchQueryRequest
            ? ((Olingo2BatchQueryRequest) request).getQueryParams()
            : null;
    final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams);

    // resolve response content
    final Object resolvedContent = content != null ? readContent(uriInfo, content) : null;

    return new Olingo2BatchResponse(
        statusCode, statusInfo, response.getContentId(), response.getHeaders(), resolvedContent);
  }