org.apache.http.client.HttpClient Java Examples

The following examples show how to use org.apache.http.client.HttpClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DCContentUploader.java    From documentum-rest-client-java with Apache License 2.0 7 votes vote down vote up
public DCContentUploader upload() throws IOException
{
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/octet-stream");
    post.setEntity(new InputStreamEntity(content));

    HttpResponse httpResponse = client.execute(post);
    status = httpResponse.getStatusLine().getStatusCode();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(httpResponse.getEntity().getContent(), os);
    response = os.toString("UTF-8");
    headers = new HttpHeaders();
    for(Header header : httpResponse.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    post.releaseConnection();
    return this;
}
 
Example #2
Source File: RunProducer.java    From NLIWOD with GNU Affero General Public License v3.0 7 votes vote down vote up
public static String stringToResource(String answer){
	try {
		ResponseToStringParser parser = new ResponseToStringParser();
		HttpClient client = HttpClientBuilder.create().build();
		URI uri = new URIBuilder().setScheme("http").setHost("dbpedia.org").setPath("/sparql")
				.setParameter("default-graph-uri", "http://dbpedia.org")
				.setParameter("query", "SELECT ?uri WHERE {?uri rdfs:label \"" + answer + "\"@en.}")
				.setParameter("format", "text/html")
				.setParameter("CXML_redir_for_subjs", "121")
				.setParameter("CSML_redir_for_hrefs", "")
				.setParameter("timeout", "30000")
				.setParameter("debug", "on")
				.build();
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response = client.execute(httpget);
		Document doc;
		doc = Jsoup.parse(parser.responseToString(response));
	return doc.select("a").attr("href");
	} catch (IllegalStateException | IOException | URISyntaxException e) {
		e.printStackTrace();
		return "";
	}
	
	
}
 
Example #3
Source File: WallWrapperServiceMediator.java    From wallpaper with GNU General Public License v2.0 7 votes vote down vote up
public static String feedback_post(String content, String contact, String version, String system, String uuid) {
	String count = "";
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost = new HttpPost("http://luhaojie.test.abab.com/index.php");//?picSize=320x510&imgSize=320x510
	List<BasicNameValuePair> valuePairs = new ArrayList<BasicNameValuePair>();
		valuePairs.add(new BasicNameValuePair("c", "AbabInterface_Sj"));
		valuePairs.add(new BasicNameValuePair("a", "Pic"));
		valuePairs.add(new BasicNameValuePair("param", "{\"content\":\"" + content + "\",\"system\":\"Android\",\"version\":\"" + version + "\",\"contact\":\"" + contact + "\",\"uuid\":\""+uuid+"\"}"));						
	try {
		httpPost.setEntity(new UrlEncodedFormEntity(valuePairs, "UTF-8"));
		httpPost.setHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=utf-8");
	} catch (UnsupportedEncodingException e2) {
		e2.printStackTrace();
	}
	try {
		HttpResponse response = httpClient.execute(httpPost);
		count = EntityUtils.toString(response.getEntity(), "utf-8");
	
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	return count;
	
}
 
Example #4
Source File: RegistrationRecaptcha.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean validateRecaptcha(ValidationContext context, boolean success, String captcha, String secret) {
    HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient();
    HttpPost post = new HttpPost("https://www." + getRecaptchaDomain(context.getAuthenticatorConfig()) + "/recaptcha/api/siteverify");
    List<NameValuePair> formparams = new LinkedList<>();
    formparams.add(new BasicNameValuePair("secret", secret));
    formparams.add(new BasicNameValuePair("response", captcha));
    formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr()));
    try {
        UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(form);
        HttpResponse response = httpClient.execute(post);
        InputStream content = response.getEntity().getContent();
        try {
            Map json = JsonSerialization.readValue(content, Map.class);
            Object val = json.get("success");
            success = Boolean.TRUE.equals(val);
        } finally {
            content.close();
        }
    } catch (Exception e) {
        ServicesLogger.LOGGER.recaptchaFailed(e);
    }
    return success;
}
 
Example #5
Source File: Util.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static String getUserInfo(ServerConfiguration serverConfiguration,
                                 AuthenticationToken token) throws IOException {

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(serverConfiguration.getUserInfoUri());

    get.setHeader("Authorization", String.format("Bearer %s", token.getAccessTokenValue()));
    HttpResponse response = httpClient.execute(get);

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

    String jsonString = "";
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        jsonString = jsonString + line;
    }
    bufferedReader.close();
    return jsonString;
}
 
Example #6
Source File: ProductDatabaseClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<String> getProducts(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/products");
        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();
    }
}
 
Example #7
Source File: AppUtil.java    From coolreader with MIT License 6 votes vote down vote up
/**
 * 获取网址内容
 * @param url
 * @return
 * @throws Exception
 */
public static String getContent(String url) throws Exception{
    StringBuilder sb = new StringBuilder();
    
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    //设置网络超时参数
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
        
        String line = null;
        while ((line = reader.readLine())!= null){
            sb.append(line + "/n");
        }
        reader.close();
    }
    return sb.toString();
}
 
Example #8
Source File: UPDATEWorker.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
private void setCredentials(UpdateProcessor exec) {
	if (exec instanceof UpdateProcessRemote && user != null && !user.isEmpty() && password != null
			&& !password.isEmpty()) {
		CredentialsProvider provider = new BasicCredentialsProvider();

		provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
				new UsernamePasswordCredentials(user, password));
		HttpContext httpContext = new BasicHttpContext();
		httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, provider);

		((UpdateProcessRemote) exec).setHttpContext(httpContext);
		HttpClient test = ((UpdateProcessRemote) exec).getClient();
		System.out.println(test);
	}

}
 
Example #9
Source File: FlashbackRunnerTest.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNotMatchMethod() throws IOException, InterruptedException {
  URL flashbackScene = getClass().getResource(FLASHBACK_SCENE_DIR);
  String rootPath = flashbackScene.getPath();
  SceneConfiguration sceneConfiguration = new SceneConfiguration(rootPath, SCENE_MODE, HTTP_SCENE);
  try (FlashbackRunner flashbackRunner = new FlashbackRunner.Builder().mode(SCENE_MODE)
      .sceneAccessLayer(
          new SceneAccessLayer(SceneFactory.create(sceneConfiguration), MatchRuleUtils.matchEntireRequest()))
      .build()) {
    flashbackRunner.start();
    HttpHost host = new HttpHost(PROXY_HOST, PROXY_PORT);
    String url = "http://www.example.org/";
    HttpClient client = HttpClientBuilder.create().setProxy(host).build();
    HttpPost post = new HttpPost(url);
    HttpResponse httpResponse = client.execute(post);
    Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 400);
    Assert.assertTrue(EntityUtils.toString(httpResponse.getEntity())
        .contains("No Matching Request"));
  }
}
 
Example #10
Source File: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 6 votes vote down vote up
private HttpResponse makeHTTPConnection() throws IOException, NullPointerException {
    if (fileURI == null) throw new NullPointerException("No file URI specified");

    HttpClient client = HttpClientBuilder.create().build();

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);

    BasicHttpContext localContext = new BasicHttpContext();

    if (null != urlParameters && (
            httpRequestMethod.equals(RequestType.PATCH) ||
                    httpRequestMethod.equals(RequestType.POST) ||
                    httpRequestMethod.equals(RequestType.PUT)
    )) {
        ((HttpEntityEnclosingRequestBase) requestMethod)
                .setEntity(new UrlEncodedFormEntity(urlParameters));
    }

    return client.execute(requestMethod, localContext);
}
 
Example #11
Source File: AbstractRestTemplateClient.java    From documentum-rest-client-java with Apache License 2.0 6 votes vote down vote up
public AbstractRestTemplateClient ignoreAuthenticateServer() {
    //backward compatible with android httpclient 4.3.x
    if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier();
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier);
            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
            ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer");
    }
    return this;
}
 
Example #12
Source File: Util.java    From AppServiceRestFul with GNU General Public License v3.0 6 votes vote down vote up
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

       SchemeRegistry registry = new SchemeRegistry(); 
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
       registry.register(new Scheme("https", sf, 443)); 

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
 
Example #13
Source File: SPARQLServiceTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private boolean isExternalEndpointAvailable() throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    String url = "http://semantic.eea.europa.eu/sparql?query=";
    String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n"
            + "SELECT * WHERE {  ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50";
    url = url + URLEncoder.encode(query, "UTF-8");
    HttpGet httpGet = new HttpGet(url);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    httpGet.setHeader("Accept", "text/xml");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        return true;
    }
    return false;
}
 
Example #14
Source File: AbstractODataRequest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an empty response that can be initialized by a stream.
 * <br/>
 * This method has to be used to build response items about a batch request.
 *
 * @param <V> ODataResponse type.
 * @return empty OData response instance.
 */
@SuppressWarnings("unchecked")
public <V extends ODataResponse> V getResponseTemplate() {
  for (Class<?> clazz : this.getClass().getDeclaredClasses()) {
    if (ODataResponse.class.isAssignableFrom(clazz)) {
      try {
        final Constructor<?> constructor = clazz.getDeclaredConstructor(
            this.getClass(), ODataClient.class, HttpClient.class, HttpResponse.class);
        constructor.setAccessible(true);
        return (V) constructor.newInstance(this, odataClient, httpClient, null);
      } catch (Exception e) {
        LOG.error("Error retrieving response class template instance", e);
      }
    }
  }

  throw new IllegalStateException("No response class template has been found");
}
 
Example #15
Source File: ApiService.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param url
 * @param requestBody
 * @param headers
 * @return
 */
public String doHttpPost(final String url, final String requestBody, final Map<String, String> headers)
{
     try {
		 HttpClient client = HttpClientBuilder.create().build();
	     HttpPost httppost = new HttpPost(url);
		 for (Map.Entry<String, String> entry : headers.entrySet()) {
			 httppost.addHeader(entry.getKey(), entry.getValue());
		 }
	     StringEntity jsonEntity = new StringEntity(requestBody);
	     httppost.setEntity(jsonEntity);
	     HttpResponse httpresponse = client.execute(httppost);
		 return EntityUtils.toString(httpresponse.getEntity());
	} catch (org.apache.http.ParseException parseException) {
		log.error("ParseException : "+parseException.getMessage());
	} catch (IOException ioException) {
		log.error("IOException : "+ioException.getMessage());
	}
	return null;
}
 
Example #16
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
public void sendPost(String url, String urlParameters) throws Exception {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost(url);
    request.addHeader("User-Agent", "Mozilla/5.0");

    List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
    String[] s = urlParameters.split("&");
    for (int i = 0; i < s.length; i++) {
        String g = s[i];
        valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1)));
    }

    request.setEntity(new UrlEncodedFormEntity(valuePairs));
    HttpResponse response = client.execute(request);
    System.out.println("Response Code: " + response.getStatusLine().getStatusCode());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String responseLine;
    while ((responseLine = bufferedReader.readLine()) != null) {
        result.append(responseLine);
    }

    System.out.println("Response: " + result.toString());
}
 
Example #17
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
public TweetList getFeed (final SuccessWhaleFeed feed, final String sinceId, final Collection<Meta> extraMetas) throws SuccessWhaleException {
		return authenticated(new SwCall<TweetList>() {
			private String url;

			@Override
			public TweetList invoke (final HttpClient client) throws IOException {
				this.url = makeAuthedUrl(API_FEED, "&sources=", URLEncoder.encode(feed.getSources(), "UTF-8"));

				// FIXME disabling this until SW finds a way to accept it on mixed feeds [issue 89].
//				if (sinceId != null) this.url += "&since_id=" + sinceId;

				final HttpGet req = new HttpGet(this.url);
				AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
				return client.execute(req, new FeedHandler(getAccount(), extraMetas));
			}

			@Override
			public String describeFailure (final Exception e) {
				return "Failed to fetch feed '" + feed + "' from '" + this.url + "': " + e.toString();
			}
		});
	}
 
Example #18
Source File: UpdateReservedCharsTask.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private HttpClient createHttpClient() {
  HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
  HttpClient client =
    clientBuilder.setSocketTimeout( WorkspaceSettings.getInstance().getConnectionTimeout() * 1000 )
      .setCredentials( loginData.getUsername(), loginData.getPassword() ).setCookieSpec( CookieSpecs.DEFAULT )
      .build();

  return client;
}
 
Example #19
Source File: SwiftManager.java    From sync-service with Apache License 2.0 5 votes vote down vote up
@Override
public void createNewWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    HttpClient httpClient = new DefaultHttpClient();

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #20
Source File: HealthCheckResourceTest.java    From karyon with Apache License 2.0 5 votes vote down vote up
private void checkHealth(HealthCheckHandler healthCheckHandler, int respStatus) throws Exception {
    final AdminResourcesContainer adminResourcesContainer = buildAdminResourcesContainer(healthCheckHandler);
    adminResourcesContainer.init();
    final int adminPort = adminResourcesContainer.getServerPort();

    HttpClient client = new DefaultHttpClient();
    HttpGet healthGet =
            new HttpGet(String.format("http://localhost:%d/jr/healthcheck", adminPort));
    HttpResponse response = client.execute(healthGet);
    assertEquals("admin resource health check resource failed.", respStatus, response.getStatusLine().getStatusCode());

    adminResourcesContainer.shutdown();
}
 
Example #21
Source File: HttpClientUtil.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * 封装HTTP PUT方法
 *
 * @param
 * @param
 * @return
 */
public static String put(String url, Map<String, String> paramMap)
        throws ClientProtocolException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(url);
    List<NameValuePair> formparams = setHttpParams(paramMap);
    UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, "UTF-8");
    httpPut.setEntity(param);
    HttpResponse response = httpClient.execute(httpPut);
    String httpEntityContent = getHttpEntityContent(response);
    httpPut.abort();
    return httpEntityContent;
}
 
Example #22
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static HttpClient createDefaultHttpClient() {
	Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
			.register("http", PlainConnectionSocketFactory.getSocketFactory())
			.register("https", SSLConnectionSocketFactory.getSocketFactory())
			.build();

	PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
	connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
	connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

	return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
 
Example #23
Source File: HodConfiguration.java    From find with MIT License 5 votes vote down vote up
@Bean
public HodServiceConfig.Builder<EntityType.Combined, TokenType.Simple> hodServiceConfigBuilder(
        final HttpClient httpClient,
        final ObjectMapper objectMapper,
        final ConfigService<HodFindConfig> configService
) {
    final URL endpoint = configService.getConfig().getHod().getEndpointUrl();

    return new HodServiceConfig.Builder<EntityType.Combined, TokenType.Simple>(endpoint.toString())
            .setHttpClient(httpClient)
            .setObjectMapper(objectMapper)
            .setTokenRepository(tokenRepository);
}
 
Example #24
Source File: InsightDataManager.java    From dx-java with MIT License 5 votes vote down vote up
/**
 * Create a HttpClient
 * 
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(DEFAULT_MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(),
            false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy()).setRetryHandler(retryHandler).disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example #25
Source File: HttpUtil.java    From common-project with Apache License 2.0 5 votes vote down vote up
public static String getRequest(String url) {
    try {
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, CHARSET_NAME);
        return result;
    } catch (Exception e) {
        logger.error("message req error", e);
        return null;
    }
}
 
Example #26
Source File: OnionGrabber.java    From OnionHarvester with GNU General Public License v3.0 5 votes vote down vote up
public Object[] getNewOnions() {
    Vector<Object> out = new Vector<>();

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

    // add request header
    request.addHeader("User-Agent", "OnionHarvester - Java Client");
    try {
        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() != 200) {
            out.add(false);
            return out.toArray();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        String temp = result.toString();
        jobj = new JSONObject(temp);
        jobj.getJSONArray("ports").iterator().forEachRemaining(o -> {
            getPorts().add(Integer.valueOf((String) o));
        });
        out.add(true);
        out.add(jobj.getString("start"));
        out.add(jobj.getString("end"));
        out.add(jobj.getString("id"));
    } catch (Exception ex) {
        out.add(false);
    } finally {
        return out.toArray();
    }
}
 
Example #27
Source File: HttpHelper.java    From homework_tester with MIT License 5 votes vote down vote up
public static HttpAnswer sendPost(String url, List<NameValuePair> nameValuePairs) throws IOException {
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", USER_AGENT);

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = client.execute(post);
    String page = getPageText(response);
    int code = response.getStatusLine().getStatusCode();

    return new HttpAnswer(page, code);
}
 
Example #28
Source File: BPMNTestUtils.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public static HttpResponse doPut(String url, Object payload, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(restUrl);
    put.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));
    put.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(put);
    return response;
}
 
Example #29
Source File: OrientNpmProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute http client request.
 */
protected HttpResponse execute(final Context context, final HttpClient client, final HttpRequestBase request)
    throws IOException
{
  String bearerToken = getRepository().facet(HttpClientFacet.class).getBearerToken();
  if (StringUtils.isNotBlank(bearerToken)) {
    request.setHeader("Authorization", "Bearer " + bearerToken);
  }
  return super.execute(context, client, request);
}
 
Example #30
Source File: CdcrReplicatorManager.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private BootstrapStatus getBoostrapStatus() throws InterruptedException {
  try {
    Replica leader = state.getClient().getZkStateReader().getLeaderRetry(targetCollection, shard, 30000); // assume same shard exists on target
    String leaderCoreUrl = leader.getCoreUrl();
    HttpClient httpClient = state.getClient().getLbClient().getHttpClient();
    try (HttpSolrClient client = new HttpSolrClient.Builder(leaderCoreUrl).withHttpClient(httpClient).build()) {
      @SuppressWarnings({"rawtypes"})
      NamedList response = sendCdcrCommand(client, CdcrParams.CdcrAction.BOOTSTRAP_STATUS);
      String status = (String) response.get(RESPONSE_STATUS);
      BootstrapStatus bootstrapStatus = BootstrapStatus.valueOf(status.toUpperCase(Locale.ROOT));
      if (bootstrapStatus == BootstrapStatus.RUNNING) {
        return BootstrapStatus.RUNNING;
      } else if (bootstrapStatus == BootstrapStatus.COMPLETED) {
        return BootstrapStatus.COMPLETED;
      } else if (bootstrapStatus == BootstrapStatus.FAILED) {
        return BootstrapStatus.FAILED;
      } else if (bootstrapStatus == BootstrapStatus.NOTFOUND) {
        log.warn("Bootstrap process was not found on target collection: {} shard: {}, leader: {}", targetCollection, shard, leaderCoreUrl);
        return BootstrapStatus.NOTFOUND;
      } else if (bootstrapStatus == BootstrapStatus.CANCELLED) {
        return BootstrapStatus.CANCELLED;
      } else {
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
            "Unknown status: " + status + " returned by BOOTSTRAP_STATUS command");
      }
    }
  } catch (Exception e) {
    log.error("Exception during bootstrap status request", e);
    return BootstrapStatus.UNKNOWN;
  }
}