org.apache.http.HttpEntity Java Examples

The following examples show how to use org.apache.http.HttpEntity. 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: MarcElasticsearchClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 7 votes vote down vote up
public void testElasticsearchRunning() throws IOException {
  MarcElasticsearchClient client = new MarcElasticsearchClient();
  HttpEntity response = client.rootRequest();
  assertNull(response.getContentEncoding());
  assertEquals("content-type", response.getContentType().getName());
  assertEquals("application/json; charset=UTF-8", response.getContentType().getValue());
  String content = EntityUtils.toString(response);
  Object jsonObject = jsonProvider.parse(content);
  // JsonPath.fileToDict(jsonObject, jsonPath);
  
  // JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache(content);
  assertEquals("elasticsearch", JsonPath.read(jsonObject, "$.cluster_name"));
  assertEquals("hTkN47N", JsonPath.read(jsonObject, "$.name"));
  assertEquals("1gxeFwIRR5-tkEXwa2wVIw", JsonPath.read(jsonObject, "$.cluster_uuid"));
  assertEquals("You Know, for Search", JsonPath.read(jsonObject, "$.tagline"));
  assertEquals("5.5.1", JsonPath.read(jsonObject, "$.version.number"));
  assertEquals("6.6.0", JsonPath.read(jsonObject, "$.version.lucene_version"));
  assertEquals(2, client.getNumberOfTweets());
}
 
Example #2
Source File: HttpToolResponse.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public HttpToolResponse(HttpResponse response, long startTime) {
    this.response = response;
    this.startTime = startTime; 
    
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.getContentLength();
            durationMillisOfFirstResponse = Duration.sinceUtc(startTime).toMilliseconds();

            ByteStreams.copy(entity.getContent(), out);
            content = out.toByteArray();

            entity.getContentLength();
        } else {
            durationMillisOfFirstResponse = Duration.sinceUtc(startTime).toMilliseconds();
            content = new byte[0];
        }
        durationMillisOfFullContent = Duration.sinceUtc(startTime).toMilliseconds();
        if (log.isTraceEnabled())
            log.trace("HttpPollValue latency "+Time.makeTimeStringRounded(durationMillisOfFirstResponse)+" / "+Time.makeTimeStringRounded(durationMillisOfFullContent)+", content size "+content.length);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example #3
Source File: HeartbeatManagerTest.java    From emissary with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnauthorizedHeartbeat() throws ClientProtocolException, IOException {
    CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
    HttpEntity mockHttpEntity = mock(HttpEntity.class);
    StatusLine mockStatusLine = mock(StatusLine.class);

    when(mockClient.execute(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(mockResponse);
    when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
    when(mockStatusLine.getStatusCode()).thenReturn(401);
    when(mockResponse.getEntity()).thenReturn(mockHttpEntity);
    String responseString = "Unauthorized heartbeat man";
    when(mockHttpEntity.getContent()).thenReturn(IOUtils.toInputStream(responseString));
    BasicHeader header1 = new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN);
    Header[] headers = new Header[] {header1};
    when(mockResponse.getHeaders(any())).thenReturn(headers);

    EmissaryClient client = new EmissaryClient(mockClient);

    String fromPlace = "EMISSARY_DIRECTORY_SERVICES.DIRECTORY.STUDY.http://localhost:8001/DirectoryPlace";
    String toPlace = "*.*.*.http://localhost:1233/DirectoryPlace";
    EmissaryResponse response = HeartbeatManager.getHeartbeat(fromPlace, toPlace, client); // use that client
    assertThat(response.getContentString(), containsString("Bad request -> status: 401 message: " + responseString));
}
 
Example #4
Source File: ImageUtils.java    From wx-crawl with Apache License 2.0 6 votes vote down vote up
public static String getString(HttpClient http, String url){
    try{
        HttpGet get=new HttpGet(url);
        HttpResponse hr=http.execute(get);
        HttpEntity he=hr.getEntity();
        if(he!=null){
            String charset=EntityUtils.getContentCharSet(he);
            InputStream is=he.getContent();
            return IOUtils.toString(is,charset);
        }
    } catch (Exception e){
        log.error("Failed to get download, {}", e);
    }
    return null;

}
 
Example #5
Source File: TargetTypesServiceImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAttributeValuesTest() throws IOException {
	AttributeValuesRequest attributeValuesRequest = getAttributeValuesRequest();
	when(config.getElasticSearch()).thenReturn(getElasticSearchProperty());
	HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
       when(response.getEntity()).thenReturn(jsonEntity);
       when(restClient.performRequest(anyString(), anyString(), any(Map.class), any(HttpEntity.class),
       Matchers.<Header>anyVararg())).thenReturn(response);
       ReflectionTestUtils.setField(targetTypesServiceImpl, "restClient", restClient);
       when(sl.getStatusCode()).thenReturn(200);
	    when(response.getStatusLine()).thenReturn(sl);
	    Map<String, Object> ruleParamDetails = Maps.newHashMap();
       when(mapper.readValue(anyString(), any(TypeReference.class))).thenReturn(ruleParamDetails);
	assertThat(targetTypesService.getAttributeValues(attributeValuesRequest), is(notNullValue()));
}
 
Example #6
Source File: OWLServerTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected HttpUriRequest createPostRequest(int n) throws URISyntaxException, UnsupportedEncodingException {
	URIBuilder uriBuilder = new URIBuilder()
		.setScheme("http")
		.setHost("localhost").setPort(9031)
		.setPath("/compareAttributeSets/");
	
	HttpPost httpost = new HttpPost(uriBuilder.build());

		//.setParameter("a", "MP:0000001")
		//.setParameter("b", "MP:0000003");
		
	int i=0;
	List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	for (OWLClass c : g.getAllOWLClasses()) {
		String id = g.getIdentifier(c);
	       
		nvps.add(new BasicNameValuePair("a", id));
		nvps.add(new BasicNameValuePair("b", id));
		i++;
		if (i >= n)
			break;
	}
	httpost.setEntity((HttpEntity) new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

	return httpost;
}
 
Example #7
Source File: TargetTypesServiceImplTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void getAllTargetTypesTest() throws Exception {
	when(targetTypesRepository.findAll()).thenReturn(getTargetTypesDetailsList());
	List<AssetGroupTargetTypes> selectedTargetTypes = getSelectedTargetTypes();
	when(config.getElasticSearch()).thenReturn(getElasticSearchProperty());
	
	HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
	when(targetTypesRepository.existsById(anyString())).thenReturn(false);
       when(response.getEntity()).thenReturn(jsonEntity);

       when(restClient.performRequest(anyString(), anyString(), any(Map.class), any(HttpEntity.class),
       Matchers.<Header>anyVararg())).thenReturn(response);
       ReflectionTestUtils.setField(targetTypesServiceImpl, "restClient", restClient);
       when(sl.getStatusCode()).thenReturn(200);
	    when(response.getStatusLine()).thenReturn(sl);
	    
	    
	    String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
	    JsonNode actualObj = new ObjectMapper().readTree(jsonString);
	    when(mapper.readTree(anyString())).thenReturn(actualObj);
	    
	assertThat(targetTypesService.getAllTargetTypes(selectedTargetTypes), is(notNullValue()));
}
 
Example #8
Source File: ElasticSearchRestDAOV5.java    From conductor with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a mapping type to an index if it does not exist.
 *
 * @param index The name of the index.
 * @param mappingType The name of the mapping type.
 * @param mappingFilename The name of the mapping file to use to add the mapping if it does not exist.
 * @throws IOException If an error occurred during requests to ES.
 */
private void addMappingToIndex(final String index, final String mappingType, final String mappingFilename) throws IOException {

    logger.info("Adding '{}' mapping to index '{}'...", mappingType, index);

    String resourcePath = "/" + index + "/_mapping/" + mappingType;

    if (doesResourceNotExist(resourcePath)) {
        InputStream stream = ElasticSearchDAOV5.class.getResourceAsStream(mappingFilename);
        byte[] mappingSource = IOUtils.toByteArray(stream);

        HttpEntity entity = new NByteArrayEntity(mappingSource, ContentType.APPLICATION_JSON);
        elasticSearchAdminClient.performRequest(HttpMethod.PUT, resourcePath, Collections.emptyMap(), entity);
        logger.info("Added '{}' mapping", mappingType);
    } else {
        logger.info("Mapping '{}' already exists", mappingType);
    }
}
 
Example #9
Source File: PlainClientTest.java    From sumk with Apache License 2.0 6 votes vote down vote up
@Test
public void plain() throws IOException {
	String charset = "GBK";
	HttpClient client = HttpClientBuilder.create().build();
	String act = "echo";
	HttpPost post = new HttpPost(getUrl(act));
	Map<String, Object> json = new HashMap<>();
	json.put("echo", "你好!!!");
	json.put("names", Arrays.asList("小明", "小张"));
	StringEntity se = new StringEntity(S.json().toJson(json), charset);
	post.setEntity(se);
	HttpResponse resp = client.execute(post);
	String line = resp.getStatusLine().toString();
	Assert.assertEquals("HTTP/1.1 200 OK", line);
	HttpEntity resEntity = resp.getEntity();
	String ret = EntityUtils.toString(resEntity, charset);
	Assert.assertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
}
 
Example #10
Source File: HttpComponentsAsyncClientHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] bufferedOutput)
		throws IOException {

	HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);

	if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
		HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
		HttpEntity requestEntity = new NByteArrayEntity(bufferedOutput);
		entityEnclosingRequest.setEntity(requestEntity);
	}

	HttpResponseFutureCallback callback = new HttpResponseFutureCallback(this.httpRequest);
	Future<HttpResponse> futureResponse = this.httpClient.execute(this.httpRequest, this.httpContext, callback);
	return new ClientHttpResponseFuture(futureResponse, callback);
}
 
Example #11
Source File: LoolFileConverter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException {

        int timeoutMillis = 5000;
        RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(timeoutMillis)
            .setConnectionRequestTimeout(timeoutMillis)
            .setSocketTimeout(timeoutMillis * 1000).build();
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf");

        HttpEntity multipart = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything")
            .build();

        httpPost.setEntity(multipart);
        CloseableHttpResponse response = client.execute(httpPost);
        byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity());
        client.close();
        return convertedFileBytes;
    }
 
Example #12
Source File: OntologyRestIT.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testDeleteVocabulary() throws Exception {
    Resource additionsGraphIRI;
    String recordId, branchId, commitId;
    ValueFactory vf = getOsgiService(ValueFactory.class);
    HttpEntity entity = createFormData("/test-vocabulary.ttl", "Test Vocabulary");

    try (CloseableHttpResponse response = uploadFile(createHttpClient(), entity)) {
        assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());
        String[] ids = parseAndValidateUploadResponse(response);
        recordId = ids[0];
        branchId = ids[1];
        commitId = ids[2];
        additionsGraphIRI = validateOntologyCreated(vf.createIRI(recordId), vf.createIRI(branchId), vf.createIRI(commitId));
    }

    try (CloseableHttpResponse response = deleteOntology(createHttpClient(), recordId)) {
        assertNotNull(response);
        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        validateOntologyDeleted(vf.createIRI(recordId), vf.createIRI(branchId), vf.createIRI(commitId), additionsGraphIRI);
    } catch (IOException | GeneralSecurityException e) {
        fail("Exception thrown: " + e.getLocalizedMessage());
    }
}
 
Example #13
Source File: DonkeyResponseHandler.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public T handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
    StatusLine statusLine = response.getStatusLine();
    HttpEntity entity = response.getEntity();

    if (statusLine.getStatusCode() >= 300) {
        String message = statusLine.getReasonPhrase();
        if (entity != null) {
            message += ": " + EntityUtils.toString(entity);
        }
        throw new HttpResponseException(statusLine.getStatusCode(), message);
    }

    if (entity == null) {
        return null;
    }

    long timestampSystem = System.currentTimeMillis();
    logger.debug("-- handleResponse() - timestamp system: {}", timestampSystem);
    Optional<Long> timestampOffset = timestamp(response).map(t -> t - timestampSystem);
    logger.debug("-- handleResponse() - timestamp offset: {}", timestampOffset);
    return handleEntityTimestampOffset(entity, timestampOffset);
}
 
Example #14
Source File: BulkV2Connection.java    From components with Apache License 2.0 6 votes vote down vote up
public JobInfoV2 updateJob(String jobId, JobStateEnum state) throws BulkV2ClientException {
    String endpoint = getRestEndpoint();
    endpoint += "jobs/ingest/" + jobId;
    UpdateJobRequest request = new UpdateJobRequest.Builder(state).build();
    try {
        HttpPatch httpPatch = (HttpPatch) createRequest(endpoint, HttpMethod.PATCH);
        StringEntity entity = new StringEntity(serializeToJson(request), ContentType.APPLICATION_JSON);

        httpPatch.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPatch);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new BulkV2ClientException(response.getStatusLine().getReasonPhrase());
        }
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            return deserializeJsonToObject(responseEntity.getContent(), JobInfoV2.class);
        } else {
            throw new IOException(MESSAGES.getMessage("error.job.info"));
        }
    } catch (BulkV2ClientException bec) {
        throw bec;
    } catch (IOException e) {
        throw new BulkV2ClientException(MESSAGES.getMessage("error.query.job"), e);
    }
}
 
Example #15
Source File: HttpClientUtil.java    From ATest with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送 post请求(带文件)
 * 
 * @param httpUrl
 *            地址
 * @param maps
 *            参数
 * @param fileLists
 *            附件
 */
public ResponseContent sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists,
		Map<String, String> headers, RequestConfig requestConfig, int executionCount, int retryInterval) {
	HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
	MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
	if (null != maps && maps.size() > 0) {
		for (String key : maps.keySet()) {
			meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
		}
	}
	for (File file : fileLists) {
		FileBody fileBody = new FileBody(file);
		meBuilder.addPart("files", fileBody);
	}
	HttpEntity reqEntity = meBuilder.build();
	httpPost.setEntity(reqEntity);
	return sendHttpPost(httpPost, headers, requestConfig, executionCount, retryInterval);
}
 
Example #16
Source File: ClientApiFunctionalTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void modifyConcurrentUsersOnHttpServer(String restServerName, int numberOfUsers) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String extSecurityrName = "";
	String body = "{\"group-name\": \"Default\", \"concurrent-request-limit\":\"" + numberOfUsers + "\"}";

	HttpPut put = new HttpPut("http://" + host + ":" + admin_Port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));
	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example #17
Source File: HttpUploader.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
    throws IOException, URISyntaxException {
  File file = new File(this.topologyPackageLocation);
  String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
  post = new HttpPost(uploaderUri);
  FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart(FILE, fileBody);
  HttpEntity entity = builder.build();
  post.setEntity(entity);
  HttpResponse response = execute(httpclient);
  String responseString = EntityUtils.toString(response.getEntity(),
      StandardCharsets.UTF_8.name());
  LOG.fine("Topology package download URI: " + responseString);

  return new URI(responseString);
}
 
Example #18
Source File: ElasticsearchSource.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void deleteScroll(String scrollId) throws IOException, StageException {
  if (scrollId == null) {
    return;
  }

  HttpEntity entity = new StringEntity(
      String.format("{\"scroll_id\":[\"%s\"]}", scrollId),
      ContentType.APPLICATION_JSON
  );
  delegate.performRequest(
    "DELETE",
    "/_search/scroll",
    conf.params,
    entity,
    delegate.getAuthenticationHeader(conf.securityConfig.securityUser.get())
  );
}
 
Example #19
Source File: ElasticsearchClientAsyncInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onAfterExecute(@Advice.Argument(5) ResponseListener responseListener,
                                   @Advice.Local("span") @Nullable Span span,
                                   @Advice.Local("wrapped") boolean wrapped,
                                   @Advice.Local("helper") @Nullable ElasticsearchRestClientInstrumentationHelper<HttpEntity, Response, ResponseListener> helper,
                                   @Advice.Thrown @Nullable Throwable t) {
    if (span != null) {
        // Deactivate in this thread. Span will be ended and reported by the listener
        span.deactivate();

        if (!wrapped) {
            // Listener is not wrapped- we need to end the span so to avoid leak and report error if occurred during method invocation
            helper.finishClientSpan(null, span, t);
        }
    }
}
 
Example #20
Source File: BasicHttpTest.java    From olingo-odata2 with Apache License 2.0 6 votes vote down vote up
@Test
public void postMethodNotAllowedWithContent() throws Exception {
  final HttpPost post = new HttpPost(URI.create(getEndpoint().toString()));
  final String xml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
          "<entry xmlns=\"" + Edm.NAMESPACE_ATOM_2005 + "\"" +
          " xmlns:m=\"" + Edm.NAMESPACE_M_2007_08 + "\"" +
          " xmlns:d=\"" + Edm.NAMESPACE_D_2007_08 + "\"" +
          " xml:base=\"https://server.at.some.domain.com/path.to.some.service/ReferenceScenario.svc/\">" +
          "</entry>";
  final HttpEntity entity = new StringEntity(xml);
  post.setEntity(entity);
  final HttpResponse response = getHttpClient().execute(post);

  assertEquals(HttpStatusCodes.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatusLine().getStatusCode());
  final String payload = StringHelper.inputStreamToString(response.getEntity().getContent());
  assertTrue(payload.contains("error"));
}
 
Example #21
Source File: ExecuteSparkInteractive.java    From nifi with Apache License 2.0 6 votes vote down vote up
private JSONObject readJSONObjectFromUrlPOST(String urlString, LivySessionService livySessionService, Map<String, String> headers, String payload)
    throws IOException, JSONException, SessionManagerException {
    HttpClient httpClient = livySessionService.getConnection();

    HttpPost request = new HttpPost(urlString);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.addHeader(entry.getKey(), entry.getValue());
    }
    HttpEntity httpEntity = new StringEntity(payload);
    request.setEntity(httpEntity);
    HttpResponse response = httpClient.execute(request);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
    }

    InputStream content = response.getEntity().getContent();
    return readAllIntoJSONObject(content);
}
 
Example #22
Source File: HttpClientUtil.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * 获得响应HTTP实体内容
 *
 * @param response
 * @return
 */
private static String getHttpEntityContent(HttpResponse response)
        throws IOException, UnsupportedEncodingException {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream is = entity.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String line = br.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line + "\n");
            line = br.readLine();
        }
        return sb.toString();
    }
    return "";
}
 
Example #23
Source File: HttpRequest.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes a HTTP GET request and returns the response string.
 * @param uri The URI containing the request URL and request parameters.
 * @return the HTTP response string after executing the GET request
 */
public static String executeGetRequest(URI uri) throws IOException {
    HttpUriRequest request = new HttpGet(uri);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();

    HttpResponse httpResponse = HttpClientBuilder.create()
                                                 .setDefaultRequestConfig(requestConfig)
                                                 .build()
                                                 .execute(request);
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity, "UTF-8");

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
    }
}
 
Example #24
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public long[] translateKeys(Internal.TranslateKeysRequest request) throws IOException {
    String path = "/internal/translate/keys";
    ByteArrayEntity body = new ByteArrayEntity(request.toByteArray());
    CloseableHttpResponse response = clientExecute("POST", path, body, protobufHeaders, "Error while posting translateKey",
            ReturnClientResponse.RAW_RESPONSE, false);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream src = entity.getContent();
        Internal.TranslateKeysResponse translateKeysResponse = Internal.TranslateKeysResponse.parseFrom(src);
        List<Long> values = translateKeysResponse.getIDsList();
        long[] result = new long[values.size()];
        int i = 0;
        for (Long v : values) {
            result[i++] = v.longValue();
        }

        return result;

    }
    throw new PilosaException("Server returned empty response");
}
 
Example #25
Source File: PastebinHandler.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
public boolean loginInternal(String userName, String password){
    HttpPost httppost = new HttpPost("http://pastebin.com/api/api_login.php");

    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("api_dev_key", DEV_KEY));
    params.add(new BasicNameValuePair("api_user_name", userName));
    params.add(new BasicNameValuePair("api_user_password", password));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if(entity != null) {
            InputStream instream = entity.getContent();
            userKey = IOUtils.toString(instream, "UTF-8");
            if(userKey.startsWith("Bad API request")) {
                Log.warning("User tried to log in into pastebin, it responded with the following: " + userKey);
                userKey = null;
                return false;
            }
            return true;
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #26
Source File: HttpClientTreadUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        CloseableHttpResponse response = httpClient.execute(httppost, context);
        try {
            // get the response body as an array of bytes
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result= EntityUtils.toString(entity);
                System.out.println(id+":::执行结果:::"+result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        log.error(id + " - error: " + e);
    }
}
 
Example #27
Source File: PlainDeserializer.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Deserializes the response content to a type which is assignable to {@link CharSequence}.</p>
 * 
 * @see AbstractDeserializer#run(InvocationContext, HttpResponse)
 */
@Override
public CharSequence deserialize(InvocationContext context, HttpResponse response) {

	try {
		
		HttpEntity entity = response.getEntity();
		return entity == null? "" :EntityUtils.toString(entity);
	} 
	catch(Exception e) {
		
		throw new DeserializerException(new StringBuilder("Plain deserialization failed for request <")
		.append(context.getRequest().getName())
		.append("> on endpoint <")
		.append(context.getEndpoint().getName())
		.append(">").toString(), e);
	}
}
 
Example #28
Source File: HttpRequest.java    From opentest with MIT License 6 votes vote down vote up
public String getResponseAsString() {
    HttpEntity responseEntity = this.response.getEntity();

    if (responseEntity != null) {
        try {
            InputStream contentStream = responseEntity.getContent();

            if (contentStream != null) {
                return IOUtils.toString(contentStream, "UTF-8");
            } else {
                return "";
            }
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Failed to get the response content for HTTP request %s %s",
                    this.httpVerb,
                    this.url), ex);
        }
    } else {
        return "";
    }
}
 
Example #29
Source File: UpdownBz.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private void premiumFileUpload() throws Exception {
    NULogger.getLogger().info("Updown.bz -> Start premium file upload");
    NUHttpPost httpPost = new NUHttpPost(ulEndpoint);
    httpPost.setEntity(createMonitoredFileEntity());
    httpPost.setHeader("Content-Type", URLConnection.guessContentTypeFromName(file.getName()));
    httpPost.setHeader("User-Agent", updownBzToAccount.getUserAgent());

    uploading();
    HttpResponse httpResponse = httpclient.execute(httpPost, httpContext);

    gettingLink();
    HttpEntity responseEntity = httpResponse.getEntity();
    NULogger.getLogger().info(httpResponse.getStatusLine().toString());

    String uploadResponse = "";
    if (responseEntity != null) {
        uploadResponse = EntityUtils.toString(responseEntity);
    }
    NULogger.getLogger().log(Level.INFO, "Updown.bz -> Upload response: {0}", uploadResponse);

    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        uploadFailed();
        throw new Exception("Updown.bz -> Uploading the file " + file.getName() + " failed");
    }

    Matcher m0 = Pattern.compile("\"id\":\"([a-zA-Z0-9]*)\"").matcher(uploadResponse);
    String fileId = m0.find() ? m0.group(1) : "";
    Matcher m1 = Pattern.compile("\"share_id\":\"([a-zA-Z0-9]*)\"").matcher(uploadResponse);
    String shareId = m1.find() ? m1.group(1) : "";

    if (shareId.length() <= 0 && fileId.length() > 0) {
        shareId = apiShareFile(fileId);
    }

    downURL = "https://updown.bz/" + shareId;
    delURL = "https://updown.bz/#!/fm";

    uploadFinished();
}
 
Example #30
Source File: PatchRequest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public PatchRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
  super(Method.PATCH, url, errorListener);
  mListener = listener;
  this.entity = entity;
  this.contentType = contentType;
  this.apiHeaders = apiHeaders;
}