Java Code Examples for org.apache.http.entity.StringEntity

The following examples show how to use org.apache.http.entity.StringEntity. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tinkerpop   Source File: GremlinServerHttpIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should200OnPOSTTransactionalGraphInStrictMode() throws Exception {
    assumeNeo4jIsPresent();

    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpPost httppost = new HttpPost(TestClientFactory.createURLString());
    httppost.addHeader("Content-Type", "application/json");
    httppost.setEntity(new StringEntity("{\"gremlin\":\"g1.addV()\",\"aliases\":{\"g1\":\"g\"}}", Consts.UTF_8));

    try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(1, node.get("result").get("data").get(GraphSONTokens.VALUEPROP).size());
    }
}
 
Example 2
Source Project: incubator-gobblin   Source File: AzkabanAjaxAPIClient.java    License: Apache License 2.0 6 votes vote down vote up
private static HttpPost preparePostRequest(String requestUrl, String sessionId, Map<String, String> params)
    throws IOException {
  // Create post request
  HttpPost postRequest = new HttpPost(requestUrl);
  StringBuilder stringEntityBuilder = new StringBuilder();
  stringEntityBuilder.append(String.format("session.id=%s", sessionId));
  for (Map.Entry<String, String> entry : params.entrySet()) {
    if (stringEntityBuilder.length() > 0) {
      stringEntityBuilder.append("&");
    }
    stringEntityBuilder.append(String.format("%s=%s", entry.getKey(), entry.getValue()));
  }
  StringEntity input = new StringEntity(stringEntityBuilder.toString());
  input.setContentType("application/x-www-form-urlencoded");
  postRequest.setEntity(input);
  postRequest.setHeader("X-Requested-With", "XMLHttpRequest");

  return postRequest;
}
 
Example 3
Source Project: kafka-topology-builder   Source File: MDSApiClient.java    License: MIT License 6 votes vote down vote up
/**
 * Remove the role (cluster or resource scoped) from the principal at the given scope/cluster.
 * No-op if the user doesn’t have the role. Callable by Admins.
 *
 * @param principal Fully-qualified KafkaPrincipal string for a user or group.
 * @param role The name of the role.
 * @param scope The request scope
 */
public void deleteRole(String principal, String role, RequestScope scope) {
  HttpDeleteWithBody request =
      new HttpDeleteWithBody(
          mdsServer + "/security/1.0/principals/" + principal + "/roles/" + role);
  request.addHeader("accept", " application/json");
  request.addHeader("Content-Type", "application/json");
  request.addHeader("Authorization", "Basic " + basicCredentials);
  LOGGER.debug("deleteRole: " + request.getURI());
  try {
    request.setEntity(new StringEntity(scope.asJson()));
    LOGGER.debug("bind.entity: " + scope.asJson());
    delete(request);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 4
@Test(dataProvider = "bindingData")
public void testCreateBindingWithInvalidExchange(String queueName, String bindingPattern)
        throws IOException, TimeoutException {
    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());
    channel.close();
    String exchangeName = "InvalidExchange";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                 .exchangeName(exchangeName);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_BAD_REQUEST);

    Error error = HttpClientHelper.getResponseMessage(response, Error.class);

    Assert.assertFalse(error.getMessage().isEmpty());
}
 
Example 5
Source Project: azure-devops-intellij   Source File: CatalogServiceImpl.java    License: MIT License 6 votes vote down vote up
private static StringEntity generateSoapQuery(final String pathSpecs, final int queryOptions) {
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<?xml version='1.0' encoding='UTF-8'?>"); //$NON-NLS-1$
    stringBuilder.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");//$NON-NLS-1$
    stringBuilder.append("<soap:Body xmlns=\"http://microsoft.com/webservices/\">");//$NON-NLS-1$
    stringBuilder.append("<QueryNodes>");//$NON-NLS-1$
    stringBuilder.append("<pathSpecs>");//$NON-NLS-1$
    stringBuilder.append("<string>" + pathSpecs + "</string>");//$NON-NLS-1$ //$NON-NLS-2$
    stringBuilder.append("</pathSpecs>");//$NON-NLS-1$
    stringBuilder.append("<queryOptions>" + queryOptions + "</queryOptions>");//$NON-NLS-1$
    stringBuilder.append("</QueryNodes>");//$NON-NLS-1$
    stringBuilder.append("</soap:Body>");//$NON-NLS-1$
    stringBuilder.append("</soap:Envelope>");//$NON-NLS-1$

    final StringEntity stringEntity = new StringEntity(stringBuilder.toString(), ContentType.create("application/soap+xml", "utf-8"));//$NON-NLS-1$ //$NON-NLS-2$
    return stringEntity;
}
 
Example 6
Source Project: ais-sdk   Source File: TokenDemo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 二维码识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
 * @param token token认证串
 * @param formFile 文件路径
 * @throws IOException
 */
public static void requestOcrQRCodeBase64(String token, String formFile) {

	// 1.构建二维码识别服务所需要的参数
	String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/qr-code";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
	try {
		byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);
		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

		// 2.传入二维码识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
		HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
		System.out.println(response);
		String content = IOUtils.toString(response.getEntity().getContent());
		System.out.println(content);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 7
Source Project: galaxy-fds-sdk-java   Source File: GalaxyFDSClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void putDomainMapping(String bucketName, String domainName, String indexName)
    throws GalaxyFDSClientException {
  ContentType contentType = ContentType.APPLICATION_JSON;
  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, (SubResource[]) null);
  HashMap<String, String> params = new HashMap<String, String>();
  params.put("domain", domainName);
  params.put("index", indexName);
  StringEntity requestEntity = getJsonStringEntity("", contentType);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    contentType, null, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.PutDomainMapping);

  fdsHttpClient.processResponse(response, null,
    "add domain mapping; bucket [" + bucketName + "], domainName [" + domainName + "]");
}
 
Example 8
Source Project: cosmic   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteCreateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(newObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example 9
Source Project: amforeas   Source File: AmforeasRestClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
public Optional<AmforeasResponse> add (String resource, String json) {
    final URI url = this.build(String.format(resource_path, root, alias, resource)).orElseThrow();
    final HttpPost req = new HttpPost(url);
    req.addHeader(this.accept);
    req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

    try {
        req.setEntity(new StringEntity(json));
    } catch (UnsupportedEncodingException e) {
        final String msg = "Failed to encode JSON body " + e.getMessage();
        l.error(msg);
        return Optional.of(new ErrorResponse(resource, Response.Status.BAD_REQUEST, msg));
    }

    return this.execute(req);
}
 
Example 10
Source Project: flowable-engine   Source File: CaseInstanceResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/testManualEvaluateCriteria.cmmn" })
public void testEvaluateCriteria() throws Exception {
    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder()
            .caseDefinitionKey("testManualEvaluateCriteria")
            .variable("someBean", new TestBean())
            .start();

    // Triggering the evaluation twice will satisfy the entry criterion for B
    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(1);

    String url = buildUrl(CmmnRestUrls.URL_CASE_INSTANCE, caseInstance.getId());
    HttpPut httpPut = new HttpPut(url);

    httpPut.setEntity(new StringEntity("{\"action\": \"evaluateCriteria\"}"));
    executeRequest(httpPut, HttpStatus.SC_OK);

    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(1);

    TestBean.RETURN_VALUE = true;
    executeRequest(httpPut, HttpStatus.SC_OK);

    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(2);
}
 
Example 11
Source Project: pacbot   Source File: PacHttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception(
					"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example 12
Source Project: gerrit-code-review-plugin   Source File: Checks.java    License: Apache License 2.0 6 votes vote down vote up
private CheckInfo performCreateOrUpdate(CheckInput input)
    throws RestApiException, URISyntaxException, ParseException, IOException {
  HttpPost request = new HttpPost(buildRequestUrl());
  String inputString =
      JsonBodyParser.createRequestBody(input, new TypeToken<CheckInput>() {}.getType());
  request.setEntity(new StringEntity(inputString));
  request.setHeader("Content-type", "application/json");

  try (CloseableHttpResponse response = client.execute(request)) {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return JsonBodyParser.parseResponse(
          EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
    }
    throw new RestApiException(
        String.format("Request returned status %s", response.getStatusLine().getStatusCode()));
  }
}
 
Example 13
Source Project: kylin   Source File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
private boolean setCache(boolean flag) throws IOException {
    String url = baseUrl + "/admin/config";
    HttpPut put = newPut(url);
    HttpResponse response = null;
    try {
        HashMap<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("key", "kylin.query.cache-enabled");
        paraMap.put("value", flag + "");
        put.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(paraMap), UTF_8));
        response = client.execute(put);
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            return false;
        } else {
            return true;
        }
    } finally {
        cleanup(put, response);
    }
}
 
Example 14
Source Project: pacbot   Source File: ESManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void createIndexTest() throws Exception{
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    when(sl.getStatusCode()).thenReturn(100);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(sl.getStatusCode()).thenReturn(200);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenThrow(new IOException());
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    esManager.createIndex("index", new ArrayList<>());
}
 
Example 15
Source Project: render   Source File: AcquisitionDataClient.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the state of the specified tiles on the acquisition server.
 *
 * @param  tileIdList  list of tile ids to update.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public void updateTileStates(final AcquisitionTileIdList tileIdList)
        throws IOException {

    final String json = tileIdList.toJson();
    final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
    final URI uri = getUri(baseUrl + "/tile-state");
    final String requestContext = "PUT " + uri;
    final EmptyResponseHandler responseHandler = new EmptyResponseHandler(requestContext);

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    LOG.info("updateTileStates: submitting {} with {}", requestContext, tileIdList);

    httpClient.execute(httpPut, responseHandler);
}
 
Example 16
Source Project: DiscordBot   Source File: Log.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method by StupPlayer (https://github.com/StupPlayer)
 * @param data
 * @return
 */
public static String hastePost(String data) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("https://hastebin.com/documents");

    try {
        post.setEntity(new StringEntity(data));

        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return "https://hastebin.com/" + new JsonParser().parse(result).getAsJsonObject().get("key").getAsString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "Could not post!";
}
 
Example 17
Source Project: nifi   Source File: ExecuteSparkInteractive.java    License: 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 18
Source Project: cosmic   Source File: RESTServiceConnectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomDeserializerForCustomLists() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}"));
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass();
    final RESTServiceConnector connector = new RESTServiceConnector.Builder()
            .client(restClient)
            .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>())
            .build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
 
Example 19
Source Project: kylin-on-parquet-v2   Source File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
private boolean setCache(boolean flag) throws IOException {
    String url = baseUrl + "/admin/config";
    HttpPut put = newPut(url);
    HttpResponse response = null;
    try {
        HashMap<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("key", "kylin.query.cache-enabled");
        paraMap.put("value", flag + "");
        put.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(paraMap), UTF_8));
        response = client.execute(put);
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            return false;
        } else {
            return true;
        }
    } finally {
        cleanup(put, response);
    }
}
 
Example 20
Source Project: apollo   Source File: NamespaceOpenApiServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNamespaces() throws Exception {
  StringEntity responseEntity = new StringEntity("[]");
  when(someHttpResponse.getEntity()).thenReturn(responseEntity);

  final ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class);

  namespaceOpenApiService.getNamespaces(someAppId, someEnv, someCluster);

  verify(httpClient, times(1)).execute(request.capture());

  HttpGet get = request.getValue();

  assertEquals(String
          .format("%s/envs/%s/apps/%s/clusters/%s/namespaces", someBaseUrl, someEnv, someAppId, someCluster),
      get.getURI().toString());
}
 
Example 21
Source Project: blynk-server   Source File: HttpAPIPinsTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiPutGetNonExistingPin() throws Exception {
    HttpPut put = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v10");
    put.setEntity(new StringEntity("[\"100\", \"101\", \"102\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(put)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpGet get = new HttpGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/v10");

    try (CloseableHttpResponse response = httpclient.execute(get)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        List<String> values = TestUtil.consumeJsonPinValues(response);
        assertEquals(3, values.size());
        assertEquals("100", values.get(0));
        assertEquals("101", values.get(1));
        assertEquals("102", values.get(2));
    }
}
 
Example 22
Source Project: beihu-boot   Source File: DingtalkChatbotClient.java    License: Apache License 2.0 6 votes vote down vote up
public SendResult send(Message message) throws IOException {
    HttpPost httppost = new HttpPost(webhook);
    httppost.addHeader("Content-Type", "application/json; charset=utf-8");
    StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
    httppost.setEntity(se);
    SendResult sendResult = new SendResult();
    HttpResponse response = this.httpclient.execute(httppost);
    if (response.getStatusLine().getStatusCode() == 200) {
        String result = EntityUtils.toString(response.getEntity());
        JSONObject obj = JSONObject.parseObject(result);
        Integer errcode = obj.getInteger("errcode");
        sendResult.setErrorCode(errcode);
        sendResult.setErrorMsg(obj.getString("errmsg"));
        sendResult.setIsSuccess(errcode.equals(0));
    }
    return sendResult;
}
 
Example 23
Source Project: elastic-rabbitmq   Source File: LoadData.java    License: MIT License 6 votes vote down vote up
public ESBulkResponse doBulkRequest(String body) {
    try {
        HttpEntity requestBody = new StringEntity(body);
        Response response = client.performRequest(
                "POST",
                ESConstants.STORE_INDEX + "/" + ESConstants.PRODUCT_TYPE + "/_bulk",
                new HashMap<String, String>(),
                requestBody);

        ESBulkResponse esResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()),
                ESBulkResponse.class);
        return esResponse;
    } catch (IOException e) {
        logger.error("Error bulk request " + e);
    }

    return null;
}
 
Example 24
/**
 * 
 * @param command
 * @param parameters
 * 
 * @return
 * 
 *         example : MultichainQueryBuidlder.executeProcess(MultichainCommand .SENDTOADDRESS,
 *         "1EyXuq2JVrj4E3CpM9iNGNSqBpZ2iTPdwGKgvf {\"rdcoin\":0.01}"
 * @throws MultichainException
 */
protected Object execute(CommandElt command, Object... parameters) throws MultichainException {

  if (httpclient != null && httppost != null) {
    try {
      // Generate Mapping of calling arguments
      Map<String, Object> entityValues = prepareMap(this.queryParameters, command, parameters);
      // Generate the entity and initialize request
      StringEntity rpcEntity = prepareRpcEntity(entityValues);
      httppost.setEntity(rpcEntity);
      // Execute the request and get the answer
      return executeRequest();

    } catch (IOException e) {
      e.printStackTrace();
      throw new MultichainException(null, e.toString());
    }
  } else {
    throw new MultichainException("Initialization Problem",
        "MultiChainCommand not initialized, please specify ip, port, user and pwd !");
  }
}
 
Example 25
Source Project: streams   Source File: TwitterSecurityTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testProcess() throws Exception {
  URI testURI = new URIBuilder()
      .setPath("/1/statuses/update.json")
      .setParameter("include_entities", "true")
      .build();
  HttpPost testRequest = new HttpPost(testURI);
  testRequest.setEntity(new StringEntity("status="+security.encode("Hello Ladies + Gentlemen, a signed OAuth request!")));
  HttpHost host = new HttpHost("api.twitter.com", -1, "https");
  HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(testRequest, host);
  TwitterOAuthConfiguration testOauthConfiguration = new TwitterOAuthConfiguration()
      .withConsumerKey("xvz1evFS4wEEPTGEFPHBog")
      .withConsumerSecret("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw")
      .withAccessToken("370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb")
      .withAccessTokenSecret("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE");
  TwitterOAuthRequestInterceptor interceptor = Mockito.spy(new TwitterOAuthRequestInterceptor(testOauthConfiguration));
  Mockito.when(interceptor.generateNonce()).thenReturn("kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg");
  Mockito.when(interceptor.generateTimestamp()).thenReturn("1318622958");
  interceptor.process(wrapper, new HttpCoreContext());
  assertEquals(1, wrapper.getHeaders("Authorization").length);
  String actual = wrapper.getFirstHeader("Authorization").getValue();
  String expected = "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\"";
  assertEquals(expected, actual);
}
 
Example 26
Source Project: calcite   Source File: ElasticsearchTransport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fetches search results given a scrollId.
 */
Function<String, ElasticsearchJson.Result> scroll() {
  return scrollId -> {
    // fetch next scroll
    final HttpPost request = new HttpPost(URI.create("/_search/scroll"));
    final ObjectNode payload = mapper.createObjectNode()
        .put("scroll", "1m")
        .put("scroll_id", scrollId);

    try {
      final String json = mapper.writeValueAsString(payload);
      request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
      return rawHttp(ElasticsearchJson.Result.class).apply(request);
    } catch (IOException e) {
      String message = String.format(Locale.ROOT, "Couldn't fetch next scroll %s", scrollId);
      throw new UncheckedIOException(message, e);
    }
  };

}
 
Example 27
Source Project: gerrit-code-review-plugin   Source File: Checks.java    License: Apache License 2.0 6 votes vote down vote up
public CheckInfo rerun(String checkerUuid, RerunInput input) throws RestApiException {
  try {
    HttpPost request = new HttpPost(buildRequestUrl(checkerUuid + "/rerun"));
    String inputString =
        JsonBodyParser.createRequestBody(input, new TypeToken<RerunInput>() {}.getType());
    request.setEntity(new StringEntity(inputString));
    request.setHeader("Content-type", "application/json");
    try (CloseableHttpResponse response = client.execute(request)) {
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return JsonBodyParser.parseResponse(
            EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
      }
      throw new RestApiException(
          String.format(
              "Request failed with status: %d", response.getStatusLine().getStatusCode()));
    }
  } catch (Exception e) {
    throw new RestApiException("Could not rerun check", e);
  }
}
 
Example 28
@Test
public void testForceAssignNewToken() throws Exception {
    login(admin.email, admin.pass);
    HttpGet request = new HttpGet(httpsAdminServerUrl + "/users/token/[email protected]&app=Blynk&dashId=79780619&deviceId=0&new=123");

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpPut put = new HttpPut(httpServerUrl + "123/update/v10");
    put.setEntity(new StringEntity("[\"100\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(put)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpGet get = new HttpGet(httpServerUrl + "123/get/v10");

    try (CloseableHttpResponse response = httpclient.execute(get)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        List<String> values = TestUtil.consumeJsonPinValues(response);
        assertEquals(1, values.size());
        assertEquals("100", values.get(0));
    }
}
 
Example 29
Source Project: gocd   Source File: RemoteRegistrationRequesterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldPassAllParametersToPostForRegistrationOfNonElasticAgent() throws IOException {
    String url = "http://cruise.com/go";
    GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
    when(response.getEntity()).thenReturn(new StringEntity(""));
    when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
    final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
    Properties properties = new Properties();
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");

    remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
    verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "", "")));
}
 
Example 30
Source Project: calcite   Source File: EmbeddedElasticsearchPolicy.java    License: Apache License 2.0 6 votes vote down vote up
void insertBulk(String index, List<ObjectNode> documents) throws IOException {
  Objects.requireNonNull(index, "index");
  Objects.requireNonNull(documents, "documents");

  if (documents.isEmpty()) {
    // nothing to process
    return;
  }

  List<String> bulk = new ArrayList<>(documents.size() * 2);
  for (ObjectNode doc: documents) {
    bulk.add(String.format(Locale.ROOT, "{\"index\": {\"_index\":\"%s\"}}", index));
    bulk.add(mapper().writeValueAsString(doc));
  }

  final StringEntity entity = new StringEntity(String.join("\n", bulk) + "\n",
      ContentType.APPLICATION_JSON);

  final Request r = new Request("POST", "/_bulk?refresh");
  r.setEntity(entity);
  restClient().performRequest(r);
}
 
Example 31
Source Project: xian   Source File: ApacheHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String post(String body) throws ConnectTimeoutException, SocketTimeoutException {
    /*
     * LOG.info(String.format(
     * "httpClient获取到的header: %s  ;   httpClient获取到的body:%s ", headers,
     * body));
     */
    if (client == null) {
        return INIT_FAIL;
    }
    HttpPost httpPost = new HttpPost(url);
    httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
    }
    String responseContent;
    try {
        StringEntity entity = new StringEntity(body == null ? "" : body, "utf-8");
        entity.setContentEncoding("utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setConfig(requestConfig);
        HttpResponse httpResponse = client.execute(httpPost);
        responseContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
    } catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
        throw connectOrReadTimeout;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        httpPost.releaseConnection();
    }
    return responseContent;
}
 
Example 32
Source Project: AthenaServing   Source File: HttpClientUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发送post请求
 *
 * @param url
 * @param params
 * @return
 */
public String sendHttpPost(String url, String params) {
    HttpPost httpPost = new HttpPost(url);
    try {
        //设置参数
        StringEntity stringEntity = new StringEntity(params, "UTF-8");
        stringEntity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(stringEntity);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this.sendHttpPost(httpPost);
}
 
Example 33
Source Project: ais-sdk   Source File: HttpJsonDataUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpEntity ObjectToHttpEntity(Object object) {
	try {
		return new StringEntity(objectMapper.writeValueAsString(object), ContentType.APPLICATION_JSON.getCharset());
	} catch (JsonProcessingException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 34
public <T> T get(String path, String entity, Class<T> clazz) throws ElasticsearchClientException
{
    String uri = String.format("http://%s:%d%s", hostname, port, path);
    log.debug(String.format("Sending GET request to %s with entity '%s'", uri, entity));

    HttpGetWithEntity request = new HttpGetWithEntity(uri);
    request.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
    request.setEntity(new StringEntity(entity, ContentType.APPLICATION_JSON));

    String content = executeRequest(request);
    T result = deserialize(content, clazz);

    return result;
}
 
Example 35
Source Project: blynk-server   Source File: HttpAPIPinsTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testPutExtraWithNoWidget() throws Exception {
    HttpPut request = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/extra/pin/v10");
    request.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
    request.setEntity(new StringEntity("[{\"timestamp\" : 123, \"value\":\"100\"}]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }
}
 
Example 36
Source Project: nano-framework   Source File: AbstractHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据请求信息创建HttpEntityEnclosingRequestBase.
 *
 * @param cls     类型Class
 * @param url     URL
 * @param headers Http请求头信息
 * @param json    JSON请求报文
 * @return HttpEntityEnclosingRequestBase
 */
protected HttpEntityEnclosingRequestBase createEntityBase(final Class<? extends HttpEntityEnclosingRequestBase> cls, final String url,
                                                          final Map<String, String> headers, final String json) {
    try {
        final HttpEntityEnclosingRequestBase entityBase = ReflectUtils.newInstance(cls, url);
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> entityBase.addHeader(key, value));
        }

        entityBase.setEntity(new StringEntity(json, APPLICATION_JSON));
        return entityBase;
    } catch (final Throwable e) {
        throw new HttpClientInvokeException(e.getMessage(), e);
    }
}
 
Example 37
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    Navigator<MutableMap<Object, Object>> j = Jsonya.newInstance().map();
    BasicHttpRequest req = (BasicHttpRequest)request;
    String url = req.getRequestLine().getUri();
    URI uri = URI.create(url);
    String method = req.getRequestLine().getMethod();
    boolean expectsPost = uri.getPath().equals("/post");
    if (expectsPost && !method.equals("POST") ||
            !expectsPost && !method.equals("GET")) {
        throw new IllegalStateException("Method " + method + " not allowed on " + url);
    }
    List<NameValuePair> params = URLEncodedUtils.parse(uri, "UTF-8");
    if (!params.isEmpty()) {
        j.push().at("args");
        for (NameValuePair param : params) {
            j.put(param.getName(), param.getValue());
        }
        j.pop();
    }
    j.put("origin", "127.0.0.1");
    j.put("url", serverUrl + url);

    response.setHeader("Content-Type", "application/json");
    response.setStatusCode(200);
    response.setEntity(new StringEntity(j.toString()));
}
 
Example 38
Source Project: metron   Source File: RestFunctions.java    License: Apache License 2.0 5 votes vote down vote up
private HttpPost buildPostRequest(RestConfig restConfig, String uriString, Object dataObject, Map<String, Object> queryParameters) throws JsonProcessingException, URISyntaxException, UnsupportedEncodingException {
  String body = getPostData(restConfig, dataObject);

  URI uri = getURI(uriString, queryParameters);
  HttpPost httpPost = new HttpPost(uri);
  httpPost.setEntity(new StringEntity(body));
  httpPost.addHeader("Accept", "application/json");
  httpPost.addHeader("Content-type", "application/json");

  return httpPost;
}
 
Example 39
Source Project: webpush-java   Source File: TestingService.java    License: MIT License 5 votes vote down vote up
/**
 * Get the notification status for the given test case.
 *
 * @param testSuiteId
 * @param testId
 * @return
 * @throws IOException
 */
public JsonArray getNotificationStatus(int testSuiteId, int testId) throws IOException {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("testSuiteId", testSuiteId);
    jsonObject.addProperty("testId", testId);

    HttpEntity entity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);

    String notificationStatus = request(baseUrl + "get-notification-status/", entity);

    return getData(notificationStatus).get("messages").getAsJsonArray();
}
 
Example 40
Source Project: teammates   Source File: BackDoor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static HttpPost createPostRequest(String url, Map<String, String[]> params, String body) {
    HttpPost post = new HttpPost(createBasicUri(url, params));

    if (body != null) {
        StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
        post.setEntity(entity);
    }

    return post;
}