private static Bitmap getCaptchaImage(HttpClient client, String captchaId)
      throws ClientProtocolException, IOException {
    final HttpGet request = new HttpGet(String.format(CAPTCHA_IMAGE, captchaId));
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Referer", REFERER);
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    final HttpResponse response = client.execute(request);

    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();

    int next;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((next = in.read()) != -1) {
      bos.write(next);
    }
    bos.flush();
    byte[] result = bos.toByteArray();

    bos.close();

    entity.consumeContent();
    return BitmapFactory.decodeByteArray(result, 0, result.length);
  }
Пример #2
0
  @Override
  public ProtocolResponse getProtocolOutput(String url, Metadata md) throws Exception {

    LOG.debug("HTTP connection manager stats {}", CONNECTION_MANAGER.getTotalStats());

    HttpGet httpget = new HttpGet(url);
    httpget.setConfig(requestConfig);

    if (md != null) {
      String ifModifiedSince = md.getFirstValue("cachedLastModified");
      if (StringUtils.isNotBlank(ifModifiedSince)) {
        httpget.addHeader("If-Modified-Since", ifModifiedSince);
      }

      String ifNoneMatch = md.getFirstValue("cachedEtag");
      if (StringUtils.isNotBlank(ifNoneMatch)) {
        httpget.addHeader("If-None-Match", ifNoneMatch);
      }
    }

    // no need to release the connection explicitly as this is handled
    // automatically. The client itself must be closed though.
    try (CloseableHttpClient httpclient = builder.build()) {
      return httpclient.execute(httpget, this);
    }
  }
Пример #3
0
  public String unTag(NewTagModel untag) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + untag.get_id());
      oldTagGet.addHeader(authHeaderKey, authHeaderValue);
      oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue);
      oldTagGet.addHeader(contentHeaderKey, contentHeaderValue);
      HttpResponse oldTagResp = httpclient.execute(oldTagGet);
      Gson gson = new Gson();
      TagModel updatedtag =
          gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class);
      httpclient.close();

      updatedtag.getTagged().remove(untag.getUsername());
      LOGGER.info(untag.get_id() + " is untagging " + untag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + untag.get_id());
      updatedTagPut.addHeader(authHeaderKey, authHeaderValue);
      updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue);
      updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue);
      updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag)));
      httpclient = HttpClients.createDefault();
      HttpResponse updatedTagResp = httpclient.execute(updatedTagPut);
      if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) {
        String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity());
        httpclient.close();
        return updatedTagEntity;
      }
      httpclient.close();
      return successJson;
    } catch (Exception e) {
      e.printStackTrace();
      return failJson;
    }
  }
 /**
  * Fill an http get request with the header information.
  *
  * @param get An http get request
  */
 public void fill(HttpGet get) {
   get.addHeader("User-Agent", user_agent);
   get.addHeader("Accept", accept);
   get.addHeader("Accept-Language", accept_language);
   get.addHeader("Accept-Encoding", accept_encoding);
   get.addHeader("Connection", connection);
 }
 public HttpGet prepareHttpGet(URI uri) {
   HttpGet httpget = new HttpGet(uri);
   httpget.addHeader("content-type", this.configuration.getContentType());
   if (!Strings.isNullOrEmpty(authHeader))
     httpget.addHeader("Authorization", String.format("Basic %s", authHeader));
   return httpget;
 }
  public static boolean authenticate() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(Account.getAuthServer());

    get.addHeader("X-Auth-User", Account.getUsername());
    get.addHeader("X-Auth-Key", Account.getApiKey());

    try {
      HttpResponse resp = httpclient.execute(get);

      if (resp.getStatusLine().getStatusCode() == 204) {
        Account.setAuthToken(resp.getFirstHeader("X-Auth-Token").getValue());
        Account.setServerUrl(resp.getFirstHeader("X-Server-Management-Url").getValue());
        Account.setStorageUrl(resp.getFirstHeader("X-Storage-Url").getValue());
        Account.setStorageToken(resp.getFirstHeader("X-Storage-Token").getValue());
        Account.setCdnManagementUrl(resp.getFirstHeader("X-Cdn-Management-Url").getValue());
        return true;
      } else {
        return false;
      }
    } catch (ClientProtocolException cpe) {
      return false;
    } catch (IOException e) {
      return false;
    }
  }
Пример #7
0
  /*取得Google Token方法*/
  public String getAuthSubToken() {
    /*建立Name Value Pair字串*/
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("Email", this.strGoogleAccount));
    nvps.add(new BasicNameValuePair("Passwd", this.strGooglePassword));
    nvps.add(new BasicNameValuePair("source", "MyApiV1"));
    nvps.add(new BasicNameValuePair("service", "cl"));
    String GoogleLoginAuth = "";
    try {
      /*建立Http Post連線*/
      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));
      response = httpclient.execute(httpost);
      if (response.getStatusLine().getStatusCode() != 200) {
        return "";
      }
      /*取回Google Token*/
      InputStream is = response.getEntity().getContent();
      GoogleLoginAuth = getAuth(is);

      /*模擬HTTP Header*/
      Header[] headers = new BasicHeader[6];
      headers[0] = new BasicHeader("Content-type", "application/x-www-form-urlencoded");
      headers[1] = new BasicHeader("Authorization", "GoogleLogin auth=\"" + GoogleLoginAuth + "\"");
      headers[2] = new BasicHeader("User-Agent", "Java/1.5.0_06");
      headers[3] =
          new BasicHeader("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
      headers[4] = new BasicHeader("Connection", "keep-alive");
      /*發出Http Get請求登入Google Calendar服務作範例*/
      HttpGet httpget;
      String feedUrl2 = "http://www.google.com/calendar/feeds/default/allcalendars/full";
      httpget = new HttpGet(feedUrl2);
      httpget.addHeader(headers[0]);
      httpget.addHeader(headers[1]);
      httpget.addHeader(headers[2]);
      httpget.addHeader(headers[3]);
      httpget.addHeader(headers[4]);
      /*取得Google Calendar服務回應*/
      response = httpclient.execute(httpget);
      String strTemp01 = convertStreamToString(response.getEntity().getContent());
      Log.i(TAG, strTemp01);
      /*指定暫存檔位置*/
      String strEarthLog = "/sdcard/googleauth.log";
      BufferedWriter bw;
      bw = new BufferedWriter(new FileWriter(strEarthLog));
      /*將取回檔案寫入暫存檔中*/
      bw.write(strTemp01, 0, strTemp01.length());
      bw.flush();

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return GoogleLoginAuth;
  }
  @Test
  public void testBundle() throws Exception {

    AuditingInterceptor interceptor = new AuditingInterceptor("HAPITEST", false);
    Map<String, Class<? extends IResourceAuditor<? extends IResource>>> auditors =
        new HashMap<String, Class<? extends IResourceAuditor<? extends IResource>>>();
    auditors.put("Patient", PatientAuditor.class);
    interceptor.setAuditableResources(auditors);
    servlet.setInterceptors(Collections.singletonList((IServerInterceptor) interceptor));

    MockDataStore mockDataStore = mock(MockDataStore.class);
    interceptor.setDataStore(mockDataStore);

    String requestURL = "http://localhost:" + ourPort + "/Patient?_id=1,2";
    HttpGet httpGet = new HttpGet(requestURL);
    httpGet.addHeader(UserInfoInterceptor.HEADER_USER_ID, "hapi-fhir-junit-user");
    httpGet.addHeader(UserInfoInterceptor.HEADER_USER_NAME, "HAPI FHIR Junit Test Cases");
    httpGet.addHeader(UserInfoInterceptor.HEADER_APPLICATION_NAME, "hapi-fhir-junit");

    HttpResponse status = ourClient.execute(httpGet);
    IOUtils.closeQuietly(status.getEntity().getContent());

    ArgumentCaptor<SecurityEvent> captor = ArgumentCaptor.forClass(SecurityEvent.class);

    verify(mockDataStore, times(1)).store(captor.capture());

    SecurityEvent auditEvent = captor.getValue();
    assertEquals(
        SecurityEventOutcomeEnum.SUCCESS.getCode(), auditEvent.getEvent().getOutcome().getValue());
    assertEquals(
        "HAPI FHIR Junit Test Cases", auditEvent.getParticipantFirstRep().getName().getValue());
    assertEquals(
        "hapi-fhir-junit-user", auditEvent.getParticipantFirstRep().getUserId().getValue());
    assertEquals("hapi-fhir-junit", auditEvent.getSource().getIdentifier().getValue());
    assertEquals("HAPITEST", auditEvent.getSource().getSite().getValue());
    assertEquals(
        SecurityEventSourceTypeEnum.USER_DEVICE.getCode(),
        auditEvent.getSource().getTypeFirstRep().getCode().getValue());

    List<ObjectElement> objects = auditEvent.getObject();
    assertEquals(2, objects.size());

    for (ObjectElement object : objects) {
      if ("00001".equals(object.getIdentifier().getValue().getValue())) {
        assertEquals("Patient: PatientOne Test", object.getName().getValue());
      } else if ("00002".equals(object.getIdentifier().getValue().getValue())) {
        assertEquals(
            "Patient: Ms Laura Elizabeth MacDougall Sookraj B.Sc.", object.getName().getValue());
      } else {
        fail(
            "Unexpected patient identifier being audited: "
                + object.getIdentifier().getValue().getValue());
      }
      assertEquals(
          requestURL, new String(Base64.decodeBase64(object.getQuery().getValueAsString())));
      assertEquals(SecurityEventObjectTypeEnum.PERSON, object.getType().getValueAsEnum());
    }
  }
Пример #9
0
 /**
  * 模拟浏览器GET提交
  *
  * @param url
  * @return
  */
 public static HttpGet getGetMethod(String url) {
   HttpGet pmethod = new HttpGet(url);
   // 设置响应头信息
   pmethod.addHeader("Connection", "keep-alive");
   pmethod.addHeader("Cache-Control", "max-age=0");
   pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
   pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
   return pmethod;
 }
  /**
   * Run the query that has been set up in this instance. Next step would be to get the results with
   * {@link getQueryResult()}
   */
  public void doQuery() {
    DefaultHttpClient client = new DefaultHttpClient();

    client
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(_targetHost.getHostName(), _targetHost.getPort()),
            new UsernamePasswordCredentials(this.getAppid(), this.getAppid()));

    URI uri;
    try {
      String full_path = getQueryPath();
      String full_query = getUrlQuery();
      uri = new URI(AZURESEARCH_SCHEME, AZURESEARCH_AUTHORITY, full_path, full_query, null);
      // Bing and java URI disagree about how to represent + in query
      // parameters. This is what we have to do instead...
      uri =
          new URI(
              uri.getScheme()
                  + "://"
                  + uri.getAuthority()
                  + uri.getPath()
                  + "?"
                  + uri.getRawQuery().replace("+", "%2b"));

      // log.log(Level.WARNING, uri.toString());
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      return;
    }

    HttpGet get = new HttpGet(uri);

    get.addHeader("Accept", "application/xml");
    get.addHeader("Content-Type", "application/xml");

    try {
      _responsePost = client.execute(get);
      _resEntity = _responsePost.getEntity();

      if (this.getProcessHTTPResults()) {
        _rawResult = loadXMLFromStream(_resEntity.getContent());
        this.loadResultsFromRawResults();
      }

      // Adding an automatic HTTP Result to String really requires
      // Apache Commons IO. That would break
      // Android compatibility. I'm not going to do that unless I
      // re-implement IOUtils.
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    }
  }
Пример #11
0
  private boolean userAuthenticated(
      final String userID, final String passKey, final String serverURL) {
    final AndroidHttpClient http = AndroidHttpClient.newInstance("TrackMe");
    final HttpGet httpGet = new HttpGet(serverURL + "/api/v1/xml/validate");
    httpGet.addHeader("userid", userID);
    httpGet.addHeader("passkey", passKey);
    int code = -1;
    String message = "";
    try {
      final HttpResponse response = http.execute(httpGet);
      Log.d(UPLOAD_SERVICE_TAG, response.getStatusLine().toString());
      code = response.getStatusLine().getStatusCode();
    } catch (final ClientProtocolException e) {
      message = "Internet not available";
      Log.d(UPLOAD_SERVICE_TAG, "Service Timeout");
    } catch (final UnknownHostException e) {
      message = "Server was not known or unreachable";
      Log.d(UPLOAD_SERVICE_TAG, "Unknown Host");
    } catch (final IllegalStateException e) {
      message = "Invalid Server URL";
      Log.d(UPLOAD_SERVICE_TAG, "Illegal");
    } catch (final IOException e) {
      code = 0;
      e.printStackTrace();
      final Intent intentNotification = new Intent(this, MainActivity.class);
      final PendingIntent pi = PendingIntent.getActivity(this, 1, intentNotification, 0);
      final NotificationManager notificationManager =
          (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      final Notification notification =
          new Notification(R.drawable.uploading, "Upload Failed", System.currentTimeMillis());
      notification.setLatestEventInfo(this, "UploadFailed", "Unknown Server Error", pi);
      notification.flags |= Notification.FLAG_AUTO_CANCEL;
      notificationManager.notify(9, notification);
    }
    http.close();

    if (code == HttpStatus.SC_OK) {
      Log.d(UPLOAD_SERVICE_TAG, "valid");
      return true;
    } else if (code == -1) {
      Log.d(UPLOAD_SERVICE_TAG, "Invalid" + " " + code);
      getApplication().startActivity(UserError.makeIntent(getBaseContext(), message));
      cancelUploadAlarm(this);
      return false;
    } else if (code == 0) {
      cancelUploadAlarm(this);
      return false;
    } else {
      message = "Invalid UserID or PassKey";
      getApplication().startActivity(UserError.makeIntent(getBaseContext(), message));
      cancelUploadAlarm(this);
      return false;
    }
  }
Пример #12
0
 /** 根据URL地址和参数创建一个httpget对象 NameValuePair可以传入key-value对应的参数 */
 public HttpGet createHttpGet(String url, String encode, NameValuePair... nameValuePairs) {
   HttpGet httpGet = null;
   if (nameValuePairs != null && nameValuePairs.length > 0) {
     String query = URLEncodedUtils.format(stripNulls(nameValuePairs), encode);
     httpGet = new HttpGet(url + "?" + query);
   } else {
     httpGet = new HttpGet(url);
   }
   httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
   httpGet.addHeader("Accept-Encoding", "gzip");
   return httpGet;
 }
Пример #13
0
  public String updateTagged(NewTagModel newtag) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      // get old tagged from cloudant
      // in NewTagModel - get_id() returns person initiating tag - getUsername() returns person to
      // tag
      HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + newtag.get_id());
      oldTagGet.addHeader(authHeaderKey, authHeaderValue);
      oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue);
      oldTagGet.addHeader(contentHeaderKey, contentHeaderValue);
      HttpResponse oldTagResp = httpclient.execute(oldTagGet);
      Gson gson = new Gson();
      TagModel updatedtag =
          gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class);
      httpclient.close();

      // check for and don't allow retagging - currently front-end design shouldn't allow for this
      // but needs to be checked on server side as well
      if (updatedtag.getTagged().contains(newtag.getUsername())) {
        LOGGER.info(
            newtag.getUsername() + " already exists in tagged list for " + updatedtag.get_id());
        return alreadyTaggedJson;
      }

      // update array of tagged in updatedtag and update entry in cloudant
      updatedtag.getTagged().add(newtag.getUsername());
      HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + newtag.get_id());
      updatedTagPut.addHeader(authHeaderKey, authHeaderValue);
      updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue);
      updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue);
      updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag)));
      httpclient = HttpClients.createDefault();
      HttpResponse updatedTagResp = httpclient.execute(updatedTagPut);
      if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) {
        String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity());
        httpclient.close();
        return updatedTagEntity;
      }
      httpclient.close();
      LOGGER.info(newtag.get_id() + " tagged " + newtag.getUsername());
      return successJson;
    } catch (Exception e) {
      try {
        httpclient.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
      return failJson;
    }
  }
  @Test(
      groups = {"wso2.am"},
      description = "Checking CORS headers in response",
      dependsOnMethods = "CheckCORSHeadersInPreFlightResponse")
  public void CheckCORSHeadersInResponse() throws Exception {
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION));
    get.addHeader("Origin", "http://localhost");
    get.addHeader("Authorization", "Bearer " + accessToken);

    HttpResponse response = httpclient.execute(get);

    assertEquals(
        response.getStatusLine().getStatusCode(), HTTP_RESPONSE_CODE_OK, "Response code mismatch.");

    Header[] responseHeaders = response.getAllHeaders();

    log.info("Response Headers: CheckCORSHeadersInResponse");
    for (Header header : responseHeaders) {
      log.info(header.getName() + " : " + header.getValue());
    }

    Header header = pickHeader(responseHeaders, ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
    assertNotNull(
        header, ACCESS_CONTROL_ALLOW_ORIGIN_HEADER + " header is not available in the response.");
    assertEquals(
        header.getValue(),
        ACCESS_CONTROL_ALLOW_ORIGIN_HEADER_VALUE,
        ACCESS_CONTROL_ALLOW_ORIGIN_HEADER + " header value mismatch.");

    header = pickHeader(responseHeaders, ACCESS_CONTROL_ALLOW_METHODS_HEADER);
    assertNotNull(
        header, ACCESS_CONTROL_ALLOW_METHODS_HEADER + " header is not available in the response.");
    assertEquals(
        header.getValue(),
        ACCESS_CONTROL_ALLOW_METHODS_HEADER_VALUE,
        ACCESS_CONTROL_ALLOW_METHODS_HEADER + " header value mismatch.");

    header = pickHeader(responseHeaders, ACCESS_CONTROL_ALLOW_HEADERS_HEADER);
    assertNotNull(
        header, ACCESS_CONTROL_ALLOW_HEADERS_HEADER + " header is not available in the response.");
    assertEquals(
        header.getValue(),
        ACCESS_CONTROL_ALLOW_HEADERS_HEADER_VALUE,
        ACCESS_CONTROL_ALLOW_HEADERS_HEADER + " header value mismatch.");

    assertNull(
        pickHeader(responseHeaders, ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER),
        ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER
            + " header is available in the response, "
            + "but it should not be.");
  }
 /** Launches an http update to the failover url. */
 private void launchHTTPUpdate(String url) throws URISyntaxException {
   if (!httpRequestControl.isRequestPending()) return;
   LOG.debug("about to issue http request method");
   HttpGet get = new HttpGet(LimeWireUtils.addLWInfoToUrl(url, applicationServices.getMyGUID()));
   get.addHeader("User-Agent", LimeWireUtils.getHttpServer());
   get.addHeader(HTTPHeaderName.CONNECTION.httpStringValue(), "close");
   httpRequestControl.requestActive();
   HttpParams params = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(params, 10000);
   HttpConnectionParams.setSoTimeout(params, 10000);
   params = new DefaultedHttpParams(params, defaultParams.get());
   httpExecutor.get().execute(get, params, new RequestHandler());
 }
Пример #16
0
 /**
  * Do get.
  *
  * @param url the url
  * @param client the client
  * @return the http response
  */
 private HttpResponse doGet(String url, DefaultHttpClient client) {
   log.info("Doing GET request in RESTInvoker");
   HttpResponse response = null;
   try {
     HttpGet getRequest = new HttpGet("url");
     String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
     getRequest.addHeader("authorization", "Basic " + encoding);
     getRequest.addHeader("accept", "application/json");
     response = client.execute(getRequest);
   } catch (IOException e) {
     log.error("Exception in GET request of REST Invoker: ", e);
   }
   return response;
 }
  @Test
  public void testAuthentication() throws IOException, ScriptException {
    final TestHttpClient client = new TestHttpClient();
    try {

      HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
      CloseableHttpResponse result = client.execute(get);
      Assert.assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
      Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
      String header = getAuthHeader(BASIC, values);
      assertEquals(BASIC + " realm=\"Test Realm\"", header);
      HttpClientUtils.readResponse(result);

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth1");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/all-auth2");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));

      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user1:password1".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals("ok", HttpClientUtils.readResponse(result));
      get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/admin");
      get.addHeader(
          AUTHORIZATION.toString(),
          BASIC + " " + FlexBase64.encodeString("user2:password2".getBytes(), false));
      result = client.execute(get);
      Assert.assertEquals(StatusCodes.FORBIDDEN, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Пример #18
0
  protected String getData(
      String url, String method, String contentType, String content, ContinuationToken cTokens) {
    try {
      HttpClient client = new DefaultHttpClient();
      HttpResponse res = null;
      url = url.replaceAll(" ", "%20");
      if (method == "GET") {
        HttpGet get = new HttpGet(url);
        get.addHeader("Authorization", token);
        get.addHeader("Content-Type", contentType);
        get.addHeader("Content-Length", content.length() + "");
        res = client.execute(get);
      } else if (method == "POST") {
        HttpPost post = new HttpPost(url);
        post.addHeader("Authorization", token);
        post.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        post.setEntity(entity);
        res = client.execute(post);
      } else if (method == "DELETE") {
        HttpDelete del = new HttpDelete(url);
        del.addHeader("Authorization", token);
        del.addHeader("Content-Type", contentType);
        res = client.execute(del);
      } else if (method == "PUT") {
        HttpPut put = new HttpPut(url);
        put.addHeader("Authorization", token);
        put.addHeader("Content-Type", contentType);
        StringEntity entity = new StringEntity(content, HTTP.UTF_8);
        put.setEntity(entity);
        res = client.execute(put);
      }
      StatusLine sl = res.getStatusLine();
      String json = "";
      if (sl.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        res.getEntity().writeTo(out);
        out.close();
        json = out.toString();
        Log.i("result", json);
        return json;
      } else {
        Log.i("error", sl.getReasonPhrase());
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return null;
  }
  @Test
  public void testApacheProxyAddressStrategy() throws Exception {

    ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp());
    HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
    HttpResponse status = ourClient.execute(httpGet);
    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("<family value=\"FAMILY\""));
    assertThat(
        responseContent,
        containsString("<fullUrl value=\"http://localhost:" + ourPort + "/Patient/1\"/>"));

    ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false));
    httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
    httpGet.addHeader("x-forwarded-host", "foo.com");
    status = ourClient.execute(httpGet);
    responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("<family value=\"FAMILY\""));
    assertThat(responseContent, containsString("<fullUrl value=\"http://foo.com/Patient/1\"/>"));

    ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps());
    httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
    httpGet.addHeader("x-forwarded-host", "foo.com");
    status = ourClient.execute(httpGet);
    responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("<family value=\"FAMILY\""));
    assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>"));

    ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false));
    httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
    httpGet.addHeader("x-forwarded-host", "foo.com");
    httpGet.addHeader("x-forwarded-proto", "https");
    status = ourClient.execute(httpGet);
    responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());
    ourLog.info(responseContent);
    assertEquals(200, status.getStatusLine().getStatusCode());
    assertThat(responseContent, containsString("<family value=\"FAMILY\""));
    assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>"));
  }
  public void performRestCall(
      String restResource, String access_token, HttpGetResponseHandler httpGetResponseHandler) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(restResource);

    try {
      httpget.addHeader("Authorization", "Bearer " + access_token);
      httpget.addHeader("Accept", "application/json");
      // Execute HTTP Get Request
      Log.d("Post url = ", httpget.getMethod());
      new ApiTask(httpclient, httpGetResponseHandler).execute(httpget);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 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;
 }
Пример #22
0
    public T call() throws Exception {
      // TODO Auto-generated method stub
      String url = loginInstanceUrl + path;
      URI uri =
          new URIBuilder(url)
              .addParameter(
                  "q",
                  "select id,name,Lead_Geo_Location__Latitude__s,Lead_Geo_Location__Longitude__s from lead where Lead_Geo_Location__Latitude__s!=null")
              .build();
      HttpGet get = new HttpGet(uri);
      get.addHeader("Content-Type", "application/json");
      get.addHeader("Authorization", "Bearer " + loginAccessToken);
      HttpResponse response = null;
      try {
        response = httpclient.execute(get);
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      String getResult = null;

      try {
        getResult = EntityUtils.toString(response.getEntity());
      } catch (IOException ioException) {
        ioException.printStackTrace();
      }
      JSONObject jsonObject = null;
      jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
      Boolean isDone = jsonObject.getBoolean("done");
      String nextQuery = jsonObject.getString("nextRecordsUrl");
      TaskResult tr = new TaskResult(isDone, nextQuery);
      JSONArray recordArray = jsonObject.getJSONArray("records");
      // System.out.println(recordArray.toString());
      for (Object o : recordArray) {
        JSONObject jo = (JSONObject) o;
        GeoWrapper gewGeoWrapper =
            new GeoWrapper(
                jo.getString("Id") + "$" + jo.getString("Name"),
                jo.getDouble("Lead_Geo_Location__Longitude__s"),
                jo.getDouble("Lead_Geo_Location__Latitude__s"));
        geoWrappers.put(gewGeoWrapper);
      }
      return (T) tr;
    }
Пример #23
0
 @Test
 public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions()
     throws ClientProtocolException, IOException {
   final HttpGet request = new HttpGet(SAMPLE_URL);
   request.addHeader(HttpHeaders.ACCEPT, "application/xml");
   response = instance.execute(request);
 }
Пример #24
0
  public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session =
        (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new HttpClientBuilder().disableTrustManager().build();
    try {
      HttpGet get =
          new HttpGet(
              AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session)
                  + "/auth/admin/realms/demo/roles");
      get.addHeader("Authorization", "Bearer " + session.getTokenString());
      try {
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != 200) {
          throw new Failure(response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
          return JsonSerialization.readValue(is, TypedList.class);
        } finally {
          is.close();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
  @Test
  public void testReqriteHostHeader() throws Exception {
    setProxyHandler(true, false);
    TestHttpClient client = new TestHttpClient();

    try {
      HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded");
      get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32");
      HttpResponse result = client.execute(get);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

      Assert.assertEquals(
          port,
          Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue()));
      Assert.assertEquals(
          "http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue());
      Assert.assertEquals(
          String.format("localhost:%d", port),
          result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue());
      Assert.assertEquals(
          DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(),
          result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue());

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Пример #26
0
    @Override
    protected String doInBackground(String... urls) {

      for (String url : urls) {
        try {
          user_name = uname.getText().toString();
          HttpClient client = new DefaultHttpClient();
          String getURL = url;
          HttpGet get = new HttpGet(getURL);
          auth =
              Base64.encodeToString(((user_name + ":" + pwd.getText()).getBytes()), Base64.NO_WRAP);
          Log.d("auth", auth);
          get.addHeader("Authorization", "Basic " + auth);
          if (get.containsHeader("Authorization")) Log.d("get", "yes");
          HttpResponse responseGet = client.execute(get);
          HttpEntity resEntityGet = responseGet.getEntity();
          response = EntityUtils.toString(resEntityGet);
          Log.d("response", response);
        } catch (Exception e) {
          e.printStackTrace();
        }
        if (response.compareTo("1") == 0) {
          Log.d("auth", "Autheticated!");
        } else {
          Log.d("auth", "Authetication failed!");
        }
      }
      return response;
    }
  /*public static double getTescoTotal(String barcode) throws JSONException
  {
  	double parsedvalue= JsonObject.getTescoProductValue(barcode);

  	//int i= Integer.parseInt(parsedvalue);
  	int total = 0;
  	while(parsedvalue!=0)
  	{
  		total+=parsedvalue;
  	}
    return total;
  }*/
  public static String getTescoProductName(String barcode) throws JSONException {
    String key = "empty";
    key = login();
    String URL = startURL + key + "&SEARCHTEXT=" + barcode;

    // InputStream is=null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL);
    request.addHeader("deviceId", deviceId);
    ResponseHandler<String> handler = new BasicResponseHandler();

    try {
      result = httpclient.execute(request, handler);
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    jObject = new JSONObject(result);

    JSONArray productinfo = jObject.getJSONArray("Products");

    String name = null;

    for (int i = 0; i < productinfo.length(); i++) {
      name = productinfo.getJSONObject(i).getString("Name").toString();
    }

    return name;
  }
Пример #28
0
 public static HttpHeaderInfo getHttpHeader(String url, Map<Object, Object> headers)
     throws ClientProtocolException, IOException {
   HttpGet httpGet = new HttpGet(url);
   if (headers != null) {
     for (Map.Entry<Object, Object> entry : headers.entrySet()) {
       httpGet.addHeader(entry.getKey() + "", entry.getValue() + "");
     }
   }
   CloseableHttpResponse response = minHttpclient.execute(httpGet);
   try {
     response.close();
     HttpHeaderInfo headerInfo = new HttpHeaderInfo();
     headerInfo.setStatus(response.getStatusLine().getStatusCode());
     headerInfo.setReasonPhrase(response.getStatusLine().getReasonPhrase());
     Header[] allHeaders = response.getAllHeaders();
     if (allHeaders != null) {
       Map<String, Object> headerMap = new HashMap<String, Object>();
       for (Header header : allHeaders) {
         headerMap.put(header.getName(), header.getValue());
       }
       headerInfo.setHeaders(headerMap);
     }
     return headerInfo;
   } finally {
     response.close();
   }
 }
  /**
   * Get the user preferences from the GPII
   *
   * @param user
   * @return
   * @throws Exception
   */
  private String getPreferencesFromServer(EasitAccount user) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpGet request =
        new HttpGet(
            environment.getProperty("flowManager.url")
                + environment.getProperty("flowManager.preferences"));

    // add the access token to the request header
    request.addHeader("Authorization", "Bearer " + user.getAccessToken());
    HttpResponse response = client.execute(request);

    // NOT Correct answer
    if (response.getStatusLine().getStatusCode() != 200) {
      throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    // Correct answer
    BufferedReader rd =
        new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
      result.append(line);
    }

    logger.info("User preferences:" + result);
    return result.toString();
  }
Пример #30
0
  public static String download(String urlStr) {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(urlStr);

    // add request header
    final String USER_AGENT =
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0";
    request.addHeader("User-Agent", USER_AGENT);
    HttpResponse response;
    try {
      response = client.execute(request);

      byte[] rawresponse = EntityUtils.toByteArray(response.getEntity());

      String encoding = HTML_Downloader.detectEncoding(new String(rawresponse));
      if (encoding != null) {
        return new String(rawresponse, encoding);
      } else {
        return new String(rawresponse, "utf8");
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
    return "";
  }