Exemplo n.º 1
1
 protected Object execute(Request request, HttpUriRequest httpReq) throws Exception {
   for (Map.Entry<String, String> entry : request.entrySet()) {
     httpReq.setHeader(entry.getKey(), entry.getValue());
   }
   HttpResponse resp = executeRequestWithTimeout(httpReq);
   HttpEntity entity = resp.getEntity();
   int status = resp.getStatusLine().getStatusCode();
   if (entity == null) {
     if (status < 400) {
       return null;
     }
     throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
   }
   Header ctypeHeader = entity.getContentType();
   if (ctypeHeader == null) { // handle broken responses with no ctype
     if (status != 200) {
       // this may happen when login failed
       throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
     }
     return null; // cannot handle responses with no ctype
   }
   String ctype = ctypeHeader.getValue();
   String disp = null;
   Header[] hdisp = resp.getHeaders("Content-Disposition");
   if (hdisp != null && hdisp.length > 0) {
     disp = hdisp[0].getValue();
   }
   return request.handleResult(status, ctype, disp, entity.getContent());
 }
Exemplo n.º 2
0
  @Test
  public void contentType() throws Exception {
    server.enqueue(
        new MockResponse()
            .setBody("<html><body><h1>Hello, World!</h1></body></html>")
            .setHeader("Content-Type", "text/html"));
    server.enqueue(
        new MockResponse()
            .setBody("{\"Message\": { \"text\": \"Hello, World!\" } }")
            .setHeader("Content-Type", "application/json"));
    server.enqueue(new MockResponse().setBody("Hello, World!"));

    HttpGet request1 = new HttpGet(server.getUrl("/").toURI());
    HttpResponse response1 = client.execute(request1);
    Header[] headers1 = response1.getHeaders("Content-Type");
    assertEquals(1, headers1.length);
    assertEquals("text/html", headers1[0].getValue());
    assertNotNull(response1.getEntity().getContentType());
    assertEquals("text/html", response1.getEntity().getContentType().getValue());

    HttpGet request2 = new HttpGet(server.getUrl("/").toURI());
    HttpResponse response2 = client.execute(request2);
    Header[] headers2 = response2.getHeaders("Content-Type");
    assertEquals(1, headers2.length);
    assertEquals("application/json", headers2[0].getValue());
    assertNotNull(response2.getEntity().getContentType());
    assertEquals("application/json", response2.getEntity().getContentType().getValue());

    HttpGet request3 = new HttpGet(server.getUrl("/").toURI());
    HttpResponse response3 = client.execute(request3);
    Header[] headers3 = response3.getHeaders("Content-Type");
    assertEquals(0, headers3.length);
    assertNull(response3.getEntity().getContentType());
  }
    private void retrieveMonitorDetails(final HttpResponse res) {
      Header[] headers = res.getHeaders(HttpHeader.LOCATION);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.location = URI.create(headers[0].getValue());
      } else {
        throw new AsyncRequestException(
            "Invalid async request response. Monitor URL '" + headers[0].getValue() + "'");
      }

      headers = res.getHeaders(HttpHeader.RETRY_AFTER);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.retryAfter = Integer.parseInt(headers[0].getValue());
      }

      headers = res.getHeaders(HttpHeader.PREFERENCE_APPLIED);
      if (ArrayUtils.isNotEmpty(headers)) {
        for (Header header : headers) {
          if (header.getValue().equalsIgnoreCase(new ODataPreferences().respondAsync())) {
            preferenceApplied = true;
          }
        }
      }
      try {
        EntityUtils.consume(res.getEntity());
      } catch (IOException ex) {
        Logger.getLogger(AsyncRequestWrapperImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
Exemplo n.º 4
0
  @Test
  public void inMemorySessionTest() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setCookieStore(new BasicCookieStore());
    final CookieHandler cookieHandler = new CookieHandler();
    try {
      final SessionCookieConfig sessionConfig = new SessionCookieConfig();
      final SessionAttachmentHandler handler =
          new SessionAttachmentHandler(new InMemorySessionManager(), sessionConfig);
      handler.setNext(
          new HttpHandler() {
            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
              final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
              Session session = manager.getSession(exchange, sessionConfig);
              if (session == null) {
                session = manager.createSession(exchange, sessionConfig);
                session.setAttribute(COUNT, 0);
              }
              Integer count = (Integer) session.getAttribute(COUNT);
              exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
              session.setAttribute(COUNT, ++count);
              HttpHandlers.executeHandler(ResponseCodeHandler.HANDLE_200, exchange);
            }
          });
      cookieHandler.setNext(handler);
      DefaultServer.setRootHandler(cookieHandler);

      HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
      HttpResponse result = client.execute(get);
      Assert.assertEquals(200, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);
      Header[] header = result.getHeaders(COUNT);
      Assert.assertEquals("0", header[0].getValue());

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
      result = client.execute(get);
      Assert.assertEquals(200, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);
      header = result.getHeaders(COUNT);
      Assert.assertEquals("1", header[0].getValue());

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
      result = client.execute(get);
      Assert.assertEquals(200, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);
      header = result.getHeaders(COUNT);
      Assert.assertEquals("2", header[0].getValue());

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Exemplo n.º 5
0
  // retrieves a group, by ID, from the server
  public static boolean fromServer(String id) {
    HttpResponse resp = Connection.getRequest("/" + tableName + "/" + id);
    if (resp == null || resp.getStatusLine().getStatusCode() != 200) return false;
    Group g = new Group();
    g._id = Integer.parseInt(resp.getHeaders("Id")[0].getValue());
    g.name = resp.getHeaders("Name")[0].getValue();
    g.desc = resp.getHeaders("Desc")[0].getValue();
    g.website = resp.getHeaders("Website")[0].getValue();
    g.globalSaved = true;

    return g.saveLocally();
  }
 public HttpGet addCookiesToChannel(HttpResponse login, HttpGet getChannel) {
   for (Header singleHeader : login.getHeaders("Set-Cookie")) {
     for (HeaderElement element : singleHeader.getElements()) {
       System.out.println(element.getName() + " : " + element.getValue());
     }
   }
   getChannel.addHeader("X-Reguested-With", "XMLHttpReguest");
   HeaderElement phpElement = login.getHeaders("Set-Cookie")[0].getElements()[0];
   String php = phpElement.getName() + "=" + phpElement.getValue();
   HeaderElement netviElement = login.getHeaders("Set-Cookie")[1].getElements()[1];
   String netvi = netviElement.getName() + "=" + netviElement.getValue();
   getChannel.addHeader("Cookie", php);
   getChannel.addHeader("Cookie", netvi);
   return getChannel;
 }
Exemplo n.º 7
0
  @Test
  public void contentEncoding() throws Exception {
    String text = "{\"Message\": { \"text\": \"Hello, World!\" } }";
    ByteArrayOutputStream bodyBytes = new ByteArrayOutputStream();
    OutputStreamWriter body =
        new OutputStreamWriter(new GZIPOutputStream(bodyBytes), Charset.forName("UTF-8"));
    body.write(text);
    body.close();
    server.enqueue(
        new MockResponse().setBody(bodyBytes.toByteArray()).setHeader("Content-Encoding", "gzip"));

    byte[] tmp = new byte[32];

    HttpGet request1 = new HttpGet(server.getUrl("/").toURI());
    request1.setHeader("Accept-encoding", "gzip"); // not transparent gzip
    HttpResponse response1 = client.execute(request1);
    Header[] headers1 = response1.getHeaders("Content-Encoding");
    assertEquals(1, headers1.length);
    assertEquals("gzip", headers1[0].getValue());
    assertNotNull(response1.getEntity().getContentEncoding());
    assertEquals("gzip", response1.getEntity().getContentEncoding().getValue());
    InputStream content = new GZIPInputStream(response1.getEntity().getContent());
    ByteArrayOutputStream rspBodyBytes = new ByteArrayOutputStream();
    for (int len = content.read(tmp); len >= 0; len = content.read(tmp)) {
      rspBodyBytes.write(tmp, 0, len);
    }
    String decodedContent = rspBodyBytes.toString("UTF-8");
    assertEquals(text, decodedContent);
  }
 public String publishMessage(String topic, String tenant, String continuationGuid, byte[] data)
     throws MessagePublishException {
   final HttpPost method = new HttpPost(this.url + topic);
   final String authToken = tenant == null ? this.capabilityToken : tenantTokens.get(tenant);
   method.addHeader(
       new BasicHeader(
           HttpHeaders.AUTHORIZATION, "Bearer " + (authToken == null ? tenant : authToken)));
   method.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "avro/binary"));
   if (continuationGuid != null) {
     method.addHeader(new BasicHeader("X-XC-MESSAGE-GUID-CONTINUATION", continuationGuid));
   }
   method.setEntity(new ByteArrayEntity(data));
   try {
     final HttpResponse response = this.client.execute(method);
     if (response.getStatusLine().getStatusCode() != 200) {
       throw new MessagePublishException(response.getStatusLine().toString());
     }
     response.getEntity().getContent().close(); // needed to be able to
     // reuse the connection
     return response.getHeaders("X-XC-MESSAGE-GUID")[0].getValue();
   } catch (ClientProtocolException e) {
     throw new MessagePublishException(e);
   } catch (IOException e) {
     throw new MessagePublishException(e);
   }
 }
Exemplo n.º 9
0
  private int parseClockSkewOffset(
      org.apache.http.HttpResponse response, AmazonServiceException exception) {
    Date deviceDate = new Date();
    Date serverDate = null;
    String serverDateStr = null;
    Header[] responseDateHeader = response.getHeaders("Date");

    try {

      if (responseDateHeader.length == 0) {
        // SQS doesn't return Date header
        serverDateStr = getServerDateFromException(exception.getMessage());
        serverDate = DateUtils.parseCompressedISO8601Date(serverDateStr);
      } else {
        serverDateStr = responseDateHeader[0].getValue();
        serverDate = DateUtils.parseRFC822Date(serverDateStr);
      }
    } catch (RuntimeException e) {
      log.warn("Unable to parse clock skew offset from response: " + serverDateStr, e);
      return 0;
    }

    long diff = deviceDate.getTime() - serverDate.getTime();
    return (int) (diff / 1000);
  }
Exemplo n.º 10
0
  // create datastream
  public Datastream createDatastream(Integer feedid, Datastream datastream) throws CosmException {
    try {
      HttpPost request =
          new HttpPost(
              API_BASE_URL_V2
                  + API_RESOURCE_FEEDS
                  + "/"
                  + feedid
                  + "/datastreams"
                  + JSON_FILE_EXTENSION);
      JSONObject jo = new JSONObject();
      jo.put("version", Cosm.VERSION);

      JSONArray ja = new JSONArray();
      ja.put(datastream.toJSONObject());
      jo.put("datastreams", ja);

      request.setEntity(new StringEntity(jo.toString()));
      HttpResponse response = this.client.execute(request);
      StatusLine statusLine = response.getStatusLine();
      if (statusLine.getStatusCode() == 201) {
        String a[] = response.getHeaders(HEADER_PARAM_LOCATION)[0].getValue().split("/");
        String datastreamid = a[a.length - 1];
        this.client.getBody(response);
        return this.getDatastream(feedid, datastreamid);
      }

      throw new HttpException(response.getStatusLine().toString());
    } catch (Exception e) {
      e.printStackTrace();
      throw new CosmException("Caught exception in create Datastream" + e.getMessage());
    }
  }
    @Override
    public R getODataResponse() {
      HttpResponse res = null;
      for (int i = 0; response == null && i < MAX_RETRY; i++) {
        res = checkMonitor(location);

        if (res.getStatusLine().getStatusCode() == HttpStatusCode.ACCEPTED.getStatusCode()) {

          final Header[] headers = res.getHeaders(HttpHeader.RETRY_AFTER);
          if (ArrayUtils.isNotEmpty(headers)) {
            this.retryAfter = Integer.parseInt(headers[0].getValue());
          }

          try {
            // wait for retry-after
            Thread.sleep(retryAfter * 1000);
          } catch (InterruptedException ignore) {
            // ignore
          }

        } else {
          location = null;
          return instantiateResponse(res);
        }
      }

      if (response == null) {
        throw new ODataClientErrorException(res == null ? null : res.getStatusLine());
      }

      return response;
    }
Exemplo n.º 12
0
  public String getCookie(String url) {
    final CookieManager cookieManager = CookieManager.getInstance();
    String cookie = cookieManager.getCookie(url);

    if (cookie == null || cookie.length() == 0) {
      final HttpHead head = new HttpHead(url);
      HttpEntity entity = null;
      try {
        final HttpResponse response = HttpManager.execute(head);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          entity = response.getEntity();

          final Header[] cookies = response.getHeaders("set-cookie");
          for (Header cooky : cookies) {
            cookieManager.setCookie(url, cooky.getValue());
          }

          CookieSyncManager.getInstance().sync();
          cookie = cookieManager.getCookie(url);
        }
      } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve cookie", e);
      } finally {
        if (entity != null) {
          try {
            entity.consumeContent();
          } catch (IOException e) {
            Log.e(LOG_TAG, "Could not retrieve cookie", e);
          }
        }
      }
    }

    return cookie;
  }
Exemplo n.º 13
0
  @Test
  public void should_head_all_resource() throws IOException {
    runWithConfiguration("rest/rest.json");

    org.apache.http.HttpResponse httpResponse = helper.headForResponse(remoteUrl("/all-resources"));
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(httpResponse.getHeaders("ETag")[0].getValue(), is("Moco"));
  }
Exemplo n.º 14
0
  private void performAuthentication(DefaultHttpClient httpClient, AuthToken authToken)
      throws IOException, AuthenticationException {
    HttpResponse resp;
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, authToken.username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, authToken.password));
    params.add(new BasicNameValuePair(PARAM_USER_TIME, "dummy"));
    final HttpEntity entity;
    try {
      entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
      // this should never happen.
      throw new IllegalStateException(e);
    }
    String uri =
        BASE_URL
            + "?"
            + URLEncodedUtils.format(
                Arrays.asList(new BasicNameValuePair(XML_ID, AUTH_XML_ID)), ENCODING);
    Log.i(TAG, "Authenticating to: " + uri);

    final HttpPost post = new HttpPost(uri);
    post.addHeader(entity.getContentType());
    post.setHeader("Accept", "*/*");
    post.setEntity(entity);
    resp = httpClient.execute(post);

    // check for bad status
    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
      throw new ParseException(
          "status after auth: "
              + resp.getStatusLine().getStatusCode()
              + " "
              + resp.getStatusLine().getReasonPhrase());
    }

    // check header redirect
    Header[] locations = resp.getHeaders(HEADER_LOCATION);
    if (locations.length != 1) {
      throw new ParseException(locations.length + " header locations received!");
    }

    String location = "https://" + DOMAIN + locations[0].getValue();
    Log.v(TAG, "location=" + location);

    UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(location);
    authToken.userId = sanitizer.getValue(PARAM_USER_ID);
    authToken.sessionId = sanitizer.getValue(PARAM_SESSION_ID);
    String redirectedXmlId = sanitizer.getValue(XML_ID);

    if (authToken.userId == null
        || authToken.userId.length() == 0
        || authToken.sessionId == null
        || authToken.sessionId.length() == 0
        || AUTH_XML_ID.equalsIgnoreCase(redirectedXmlId)) {
      checkAuthError(sanitizer);
    }
  }
Exemplo n.º 15
0
  @Test
  public void headers() throws Exception {
    server.enqueue(new MockResponse().addHeader("Foo", "Bar"));
    server.enqueue(new MockResponse().addHeader("Foo", "Bar").addHeader("Foo", "Baz"));

    HttpGet request1 = new HttpGet(server.getUrl("/").toURI());
    HttpResponse response1 = client.execute(request1);
    Header[] headers1 = response1.getHeaders("Foo");
    assertEquals(1, headers1.length);
    assertEquals("Bar", headers1[0].getValue());

    HttpGet request2 = new HttpGet(server.getUrl("/").toURI());
    HttpResponse response2 = client.execute(request2);
    Header[] headers2 = response2.getHeaders("Foo");
    assertEquals(2, headers2.length);
    assertEquals("Bar", headers2[0].getValue());
    assertEquals("Baz", headers2[1].getValue());
  }
Exemplo n.º 16
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It doesn't try to login
   * using SPNEGO - it uses FORM authn directly.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWoSPNEGO(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      final HttpGet httpGet = new HttpGet(url);
      HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      assertNotNull(unauthorizedPageBody);
      LOGGER.info(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      response = httpClient.execute(httpPost);
      statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Exemplo n.º 17
0
  /**
   * Helper method to check that a response has the default X-FRAME-OPTIONS and
   * Content-Security-Policy headers. If your test doesn't use the default security policy, you get
   * to roll your own validation of that, of course.
   *
   * <p>Asserts if anything is wrong.
   *
   * <p>As a safety provision, if the config adapter *isn't* recognized as "ours," we don't check
   * anything. (This covers the fact that inside SFDC, we have a different config adapter with a
   * different default CSP.)
   *
   * @param response
   * @param guarded If {@code true}, check that we HAVE headers. If {@code false}, check that they
   *     are absent.
   * @param allowInline Allows inline script-src and style-src
   */
  protected void assertDefaultAntiClickjacking(
      HttpResponse response, boolean guarded, boolean allowInline) {
    String adapterClassName = Aura.getConfigAdapter().getClass().getName();
    if (adapterClassName.equals("org.auraframework.impl.adapter.ConfigAdapterImpl")
        || adapterClassName.equals("org.auraframework.impl.adapter.MockConfigAdapterImpl")) {
      Header[] headers = response.getHeaders("X-FRAME-OPTIONS");
      if (guarded) {
        Map<String, String> csp = getCSP(response);
        assertEquals("frame-ancestors is wrong", "'self'", csp.get("frame-ancestors"));
        if (allowInline) {
          assertEquals(
              "script-src is wrong",
              "'self' chrome-extension: 'unsafe-eval' 'unsafe-inline'",
              csp.get("script-src"));
          assertEquals(
              "style-src is wrong",
              "'self' chrome-extension: 'unsafe-inline'",
              csp.get("style-src"));
        } else {
          assertEquals("script-src is wrong", "'self' chrome-extension:", csp.get("script-src"));
          assertEquals("style-src is wrong", "'self' chrome-extension:", csp.get("style-src"));
        }
        // These maybe aren't strictly "anti-clickjacking", but since we're testing the rest of the
        // default CSP:
        assertEquals("font-src is wrong", "*", csp.get("font-src"));
        assertEquals("img-src is wrong", "*", csp.get("img-src"));
        assertEquals("media-src is wrong", "*", csp.get("media-src"));
        assertEquals("default-src is wrong", "'self'", csp.get("default-src"));
        assertEquals("object-src is wrong", "'self'", csp.get("object-src"));
        assertEquals(
            "connect-src is wrong",
            "'self' http://invalid.salesforce.com http://offline https://offline",
            csp.get("connect-src"));

        assertEquals("wrong number of X-FRAME-OPTIONS header lines", 1, headers.length);
        assertEquals("SAMEORIGIN", headers[0].getValue());
      } else {
        headers = response.getHeaders("Content-Security-Policy");
        assertEquals(0, headers.length);
        // Check X-FRAME-OPTIONS vis-a-vis CSP
        assertEquals("wrong number of X-FRAME-OPTIONS header lines", 0, headers.length);
      }
    }
  }
Exemplo n.º 18
0
 @Then("^the user should receive a specified JSON content$")
 public void jsonResponse() throws Exception {
   assertThat(response.getHeaders("Content-Type"))
       .extracting(Header::getValue)
       .containsExactly(org.apache.http.entity.ContentType.APPLICATION_JSON.toString());
   DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
   assertThat(jsonPath.<String>read("blobId")).isEqualTo(_1M_ZEROED_FILE_BLOB_ID);
   assertThat(jsonPath.<String>read("type")).isEqualTo("application/octet-stream");
   assertThat(jsonPath.<Integer>read("size")).isEqualTo(_1M);
 }
Exemplo n.º 19
0
 private static Set<String> getConnectionTokensFromResponse(HttpResponse resp) {
   Set<String> result = new HashSet<String>();
   for (Header header : resp.getHeaders(CONNECTION_HEADER)) {
     for (HeaderElement element : header.getElements()) {
       // RFC 2616 14.10: connection tokens don't have values
       result.add(element.getName().toLowerCase());
     }
   }
   return result;
 }
Exemplo n.º 20
0
 private void runPathTest(
     TestHttpClient client,
     String path,
     String expectedMatch,
     String expectedRemaining,
     Map<String, String> queryParams)
     throws IOException {
   HttpResponse result;
   HttpGet get = new HttpGet(DefaultServer.getDefaultServerAddress() + path);
   result = client.execute(get);
   Assert.assertEquals(200, result.getStatusLine().getStatusCode());
   Header[] header = result.getHeaders(MATCHED);
   Assert.assertEquals(expectedMatch, header[0].getValue());
   header = result.getHeaders(PATH);
   Assert.assertEquals(expectedRemaining, header[0].getValue());
   HttpClientUtils.readResponse(result);
   for (Map.Entry<String, String> entry : queryParams.entrySet()) {
     header = result.getHeaders(entry.getKey());
     Assert.assertEquals(entry.getValue(), header[0].getValue());
   }
 }
Exemplo n.º 21
0
  @Test
  public void should_head() throws IOException {
    runWithConfiguration("rest/rest.json");

    final Plain resource1 = new Plain();
    resource1.code = 1;
    resource1.message = "hello";

    org.apache.http.HttpResponse httpResponse = helper.headForResponse(remoteUrl("/targets/1"));
    assertThat(httpResponse.getStatusLine().getStatusCode(), is(200));
    assertThat(httpResponse.getHeaders("ETag")[0].getValue(), is("Moco"));
  }
Exemplo n.º 22
0
 /**
  * Helper to take the Content-Security-Policy header and break it into its individual components.
  * If the header is missing, this will fail the test with an assertion. Otherwise, a map keyed by
  * the various CSP directives (script-src, style-src, etc.) with the literal values of each
  * directive is returned.
  *
  * @param response
  * @return a map of directive to value.
  */
 protected Map<String, String> getCSP(HttpResponse response) {
   Header[] headers = response.getHeaders("Content-Security-Policy");
   assertEquals("wrong number of CSP header lines", 1, headers.length);
   String[] split = headers[0].getValue().split(";");
   Map<String, String> csp = new HashMap<>();
   for (String term : split) {
     term = term.trim();
     String word = term.substring(0, term.indexOf(' '));
     csp.put(word, term.substring(word.length() + 1));
   }
   return csp;
 }
Exemplo n.º 23
0
  /**
   * post方式请求数据.发送的是json数据
   *
   * @param url
   * @param params
   * @return
   */
  public static String sendhttpByPost(String url, String params) {

    HttpPost httpRequest = new HttpPost(url);
    httpRequest.addHeader("Accept-Encoding", "gzip");
    httpRequest.addHeader("Content-Type", "application/json");
    String strResult = null;
    try {

      // 发出HTTP request
      //			httpRequest.setEntity(new StringEntity(params, "UTF-8"));
      //			System.out.println("post发送的params是:" + params);
      //			url =

      HttpClient httpClient = null;
      // 判断请求协议方式
      if (url.startsWith("https://")) {
        // 取得HTTP response
        httpClient = HttpUtil.wrapClient(new DefaultHttpClient());
      } else {
        httpClient = new DefaultHttpClient();
      }
      // https请求方式
      HttpResponse httpResponse = httpClient.execute(httpRequest);
      // 若状态码为200 ok
      // Content-Encoding
      if (httpResponse.getStatusLine().getStatusCode() == 200) {
        Header[] headers = httpResponse.getHeaders("Content-Encoding");
        boolean isUseGzip = false;
        for (Header header : headers) {
          if ("Content-Encoding".equals(header.getName())) {
            if ("gzip".equalsIgnoreCase(header.getValue())) {
              isUseGzip = true;
            }
          }
        }
        if (isUseGzip) {
          strResult =
              IoUtil.convertStreamToString(
                  new GZIPInputStream(httpResponse.getEntity().getContent()));
        } else {
          strResult = EntityUtils.toString(httpResponse.getEntity());
        }
      } else {
        return null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return strResult;
  }
Exemplo n.º 24
0
 public <T extends QiitaResponse> PageableResponse<T> getPageableContents(
     URI uri, Class<T> responseType) throws IOException, QiitaException {
   HttpGet request = new HttpGet(uri);
   HttpResponse response = execute(request);
   verifyStatusCode(response, SC_OK);
   String[] linkHeaderValues = getHeaderValues(response.getHeaders("Link"));
   try (InputStream in = response.getEntity().getContent()) {
     @SuppressWarnings("unchecked")
     T[] contents = JSON.decode(in, (Class<T[]>) Array.newInstance(responseType, 0).getClass());
     return new PageableResponse<>(this, responseType, contents, linkHeaderValues);
   }
 }
  // Interface to AsyncHttpRequest
  @Override
  protected void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    byte[] responseBody = null;
    if (contentTypeHeaders.length != 1) {
      // malformed/ambiguous HTTP Header, ABORT!
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(
              status.getStatusCode(), "None, or more than one, Content-Type Header found!"),
          (String) null);
      return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
      if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
        foundAllowedContentType = true;
      }
    }
    if (!foundAllowedContentType) {
      // Content-Type not in allowed list, ABORT!
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"),
          (String) null);
      return;
    }
    try {
      HttpEntity entity = null;
      HttpEntity temp = response.getEntity();
      if (temp != null) {
        entity = new BufferedHttpEntity(temp);
      }
      responseBody = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
      sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), e, (byte[]) null);
    }

    if (status.getStatusCode() >= 300) {
      sendFailureMessage(
          status.getStatusCode(),
          response.getAllHeaders(),
          new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
          responseBody);
    } else {
      sendSuccessMessage(status.getStatusCode(), responseBody);
    }
  }
Exemplo n.º 26
0
 public static final void assert110WarningFound(HttpResponse response) {
   boolean found110Warning = false;
   for (Header h : response.getHeaders("Warning")) {
     for (HeaderElement elt : h.getElements()) {
       String[] parts = elt.getName().split("\\s");
       if ("110".equals(parts[0])) {
         found110Warning = true;
         break;
       }
     }
   }
   Assert.assertTrue(found110Warning);
 }
Exemplo n.º 27
0
  @Test
  public void jsonTransparentGzipResponse() throws Exception {
    String text = "{\"Message\": { \"text\": \"Hello, World!\" } }";
    ByteArrayOutputStream bodyBytes = new ByteArrayOutputStream();
    OutputStreamWriter body =
        new OutputStreamWriter(new GZIPOutputStream(bodyBytes), Charset.forName("UTF-8"));
    body.write(text);
    body.close();
    server.enqueue(
        new MockResponse()
            .setBody(bodyBytes.toByteArray())
            .setHeader("Content-Encoding", "gzip")
            .setHeader("Content-Type", "application/json"));

    byte[] tmp = new byte[32];

    HttpGet request1 = new HttpGet(server.getUrl("/").toURI());
    // expecting transparent gzip response by not adding header "Accept-encoding: gzip"
    HttpResponse response1 = client.execute(request1);
    Header[] headers1a = response1.getHeaders("Content-Encoding");
    assertEquals(0, headers1a.length);
    assertNull(response1.getEntity().getContentEncoding());
    // content length should also be absent
    Header[] headers1b = response1.getHeaders("Content-Length");
    assertEquals(0, headers1b.length);
    assertTrue(response1.getEntity().getContentLength() < 0);
    Header[] headers1c = response1.getHeaders("Content-Type");
    assertEquals(1, headers1c.length);
    assertEquals("application/json", headers1c[0].getValue());
    assertNotNull(response1.getEntity().getContentType());
    assertEquals("application/json", response1.getEntity().getContentType().getValue());
    InputStream content = response1.getEntity().getContent();
    ByteArrayOutputStream rspBodyBytes = new ByteArrayOutputStream();
    for (int len = content.read(tmp); len >= 0; len = content.read(tmp)) {
      rspBodyBytes.write(tmp, 0, len);
    }
    String decodedContent = rspBodyBytes.toString("UTF-8");
    assertEquals(text, decodedContent);
  }
Exemplo n.º 28
0
  /** Access http://localhost/ */
  public static String hitRootContext(Logger log, URL url, String serverName) throws Exception {
    HttpGet httpget = new HttpGet(url.toURI());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpget.setHeader("Host", serverName);

    log.info("executing request" + httpget.getRequestLine());
    HttpResponse response = httpclient.execute(httpget);

    int statusCode = response.getStatusLine().getStatusCode();
    Header[] errorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK);
    assertTrue(
        "X-Exception(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0);

    return EntityUtils.toString(response.getEntity());
  }
 public void runTest(final String theMessage) throws IOException {
   ContentEncodingHttpClient client = new ContentEncodingHttpClient();
   try {
     message = theMessage;
     HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
     get.setHeader(Headers.ACCEPT_ENCODING_STRING, "deflate");
     HttpResponse result = client.execute(get);
     Assert.assertEquals(200, result.getStatusLine().getStatusCode());
     Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
     Assert.assertEquals("deflate", header[0].getValue());
     final String body = HttpClientUtils.readResponse(result);
     Assert.assertEquals(theMessage, body);
   } finally {
     client.getConnectionManager().shutdown();
   }
 }
Exemplo n.º 30
0
 private void showUpdatesStatus(Future<HttpResponse> status) {
   String versionMsg = "<h3 align=center>Cannot get version information </h3>";
   try {
     HttpResponse response = status.get();
     updateStatusLabel.setText("");
     String file = null;
     for (Header header : response.getHeaders("Content-Disposition")) {
       Matcher matcher = Pattern.compile("filename=\"([^\"]+)\"").matcher(header.getValue());
       while (matcher.find()) {
         file = matcher.group(1);
       }
     }
     if (file != null) {
       String[] installerPatterns = {
         "PdfMetadataEditor-(\\d+)\\.(\\d+)\\.(\\d+)-installer.jar",
         "pdf-metadata-edit-(\\d+)\\.(\\d+)\\.(\\d+)-installer.jar",
       };
       Version.VersionTuple current = Version.get();
       Version.VersionTuple latest = null;
       for (String pattern : installerPatterns) {
         latest = new Version.VersionTuple(file, pattern);
         if (latest.parseSuccess) {
           break;
         }
       }
       if (current.cmp(latest) < 0) {
         versionMsg =
             "<h3 align=center>New version available: <a href='http://broken-by.me/pdf-metadata-editor/#download'>"
                 + latest.getAsString()
                 + "</a> , current: "
                 + current.getAsString()
                 + "</h3>";
         updateStatusLabel.setText("Newer version available:" + latest.getAsString());
       } else {
         versionMsg =
             "<h3 align=center>Version " + current.getAsString() + " is the latest version</h3>";
       }
     }
   } catch (InterruptedException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
   } catch (ExecutionException e1) {
     versionMsg += "<h4 align=center>Error: " + e1.getCause().getLocalizedMessage() + "</h4>";
   } finally {
     txtpnDf.setText(aboutMsg + versionMsg);
   }
 }