Java 类org.apache.http.entity.StringEntity 实例源码

项目:safecharge-java    文件:SafechargeRequestExecutor.java   
/**
 * Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}.
 * The request type is determined by the {@code headers} param.
 *
 * @param request    A {@link String} representation of a request object. Can be JSON object, form data, etc...
 * @param serviceUrl The service URL to sent the request to
 * @param headers    An array of {@link Header} objects, used to determine the request type
 * @return {@link String} response from the service (representing JSON object)
 * @throws IOException if the connection is interrupted or the response is unparsable
 */
public String executeRequest(String request, String serviceUrl, Header[] headers) throws IOException {
    HttpPost httpPost = new HttpPost(serviceUrl);
    httpPost.setHeaders(headers);
    httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8")));

    if (logger.isDebugEnabled()) {
        logger.debug("Sent " + request);
    }

    HttpResponse response = httpClient.execute(httpPost);

    String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET);
    if (logger.isDebugEnabled()) {
        logger.debug("Received " + responseJSON);
    }
    return responseJSON;
}
项目:Thrush    文件:HttpRequest.java   
public static String checkRandCodeAnsyn(String randCode) {
    Objects.requireNonNull(randCode);
    ResultManager.touch(randCode, "confirmRandCode");

    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkRandCodeAnsyn);

    httpPost.addHeader(CookieManager.cookieHeader());
    httpPost.setEntity(new StringEntity(checkRandCodeAnsynParam(), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        result = EntityUtils.toString(response.getEntity());
        logger.debug(result);
    } catch (IOException e) {
        logger.error("checkRandCodeAnsyn error", e);
    }

    return result;
}
项目:open-kilda    文件:Mininet.java   
/**
 * Simple Http Post.
 *
 * @param path the path
 * @param payload the payload
 * @return the closeable http response
 * @throws URISyntaxException the URI syntax exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MininetException the MininetException
 */
public CloseableHttpResponse simplePost(String path, String payload) 
    throws URISyntaxException, IOException, MininetException {
  URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(mininetServerIP.toString())
      .setPort(mininetServerPort.getPort())
      .setPath(path)
      .build();
  CloseableHttpClient client = HttpClientBuilder.create().build();
  RequestConfig config = RequestConfig
      .custom()
      .setConnectTimeout(CONNECTION_TIMEOUT_MS)
      .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
      .setSocketTimeout(CONNECTION_TIMEOUT_MS)
      .build();
  HttpPost request = new HttpPost(uri);
  request.setConfig(config);
  request.addHeader("Content-Type", "application/json");
  request.setEntity(new StringEntity(payload));
  CloseableHttpResponse response = client.execute(request);
  if (response.getStatusLine().getStatusCode() >= 300) {
    throw new MininetException(String.format("failure - received a %d for %s.", 
        response.getStatusLine().getStatusCode(), request.getURI().toString()));
  }
  return response;
}
项目:saluki    文件:ServiceTestController.java   
@RequestMapping(value = "testService", method = RequestMethod.POST)
public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort,
    @RequestBody GrpcServiceTestModel model) throws Exception {
  String serviceUrl = "http://" + ipPort + "/service/test";
  HttpPost request = new HttpPost(serviceUrl);
  request.addHeader("content-type", "application/json");
  request.addHeader("Accept", "application/json");
  try {
    StringEntity entity = new StringEntity(gson.toJson(model), "utf-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    request.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(request);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      String minitorJson = EntityUtils.toString(httpResponse.getEntity());
      Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType());
      return response;
    }
  } catch (Exception e) {
    throw e;
  }
  return null;
}
项目:ants    文件:Client.java   
public boolean postMessage(String url, String message) {
    boolean ret = true;

    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(URL + url);

        StringEntity se = new StringEntity(message);

        httpPost.setEntity(se);

        CloseableHttpResponse response = client.execute(httpPost);

        if (response.getStatusLine().getStatusCode() != 200) {
            ret = false;
        }

        client.close();
    } catch (Exception e) {
        e.printStackTrace();
        ret = false;
        System.exit(-1);
    }

    return ret;
}
项目:dhus-core    文件:TestInterruptibleHttpClient.java   
/**
 * Starts the HTTP server.
 *
 * @return the listening port.
 */
static int start () throws IOException
{

   server = ServerBootstrap.bootstrap ().registerHandler ("*",
         new HttpRequestHandler ()
         {

            @Override
            public void handle (HttpRequest request, HttpResponse response,
                  HttpContext context)
                  throws HttpException, IOException
            {

               response.setStatusCode (HttpStatus.SC_OK);
               response.setEntity (new StringEntity ("0123456789"));
            }
         })
         .create ();
   server.start ();

   return server.getLocalPort ();
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Adds a document to the specified ElasticSearch index / type
 * 
 * @param indexName
 *            the index name to augment
 * @param typeName
 *            the type name to augment
 * @param id
 *            the id of the document to add
 * @param jsonDocument
 *            the String JSON document to add
 */
protected static void addDocument(String indexName, String typeName, Integer id, String jsonDocument) {
    try {
        String documentEndpoint = String.format("/%s/%s/%d", indexName, typeName, id);
        StringEntity requestBody = new StringEntity(jsonDocument);
        Map<String, String> params = new HashMap<String, String>();

        Response resp = client.performRequest("PUT", documentEndpoint, params, requestBody, contentTypeHeader);
        staticLogger.debug("Response: " + resp.getStatusLine());

    } catch (IOException e) {
        // Ignore this...? probably already exists
        staticLogger.error(e.getMessage(), e);

        if (e instanceof UnsupportedEncodingException) {
            staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
            return;
        }
    }
}
项目:FaceDistinguish    文件:HttpUtils.java   
/**
 * Post String
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, 
        Map<String, String> headers, 
        Map<String, String> querys, 
        String body)
           throws Exception {       
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
       }

       if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
       }

       return httpClient.execute(request);
   }
项目:smart_plan    文件:DatabaseTableRequestHandler.java   
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    Log.d("plan", "DatabaseTableRequestHandler");
    DatabaseEntity entity;
    String uri = request.getRequestLine().getUri();
    String key =  Uri.parse(uri).getQueryParameter("database_name");
    if (!TextUtils.isEmpty(key)) {
        entity = getTableResponse(key.trim());
    }  else {
        entity = new DatabaseEntity();
        entity.setCode(BaseEntity.FAILURE_CODE);
        entity.setDataList(new ArrayList<SimpleNameEntity>());
    }
    String result = ParserJson.getSafeJsonStr(entity);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(result, "utf-8"));
}
项目:smart_plan    文件:DatabaseDataRequestHandler.java   
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    RequestLine line = request.getRequestLine();
    Uri uri = Uri.parse(line.getUri());
    DatabaseDataEntity entity;
    if (uri != null) {
        String database = uri.getQueryParameter("database");
        String tableName = uri.getQueryParameter("table");
        entity = getDataResponse(database, tableName);
        if (entity != null) {
            response.setStatusCode(200);
            response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
            return;
        }
    }
    entity = new DatabaseDataEntity();
    entity.setDataList(new ArrayList<Map<String, String>>());
    entity.setCode(BaseEntity.FAILURE_CODE);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
项目:Thrush    文件:HttpRequest.java   
public static String login(String randCode) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.loginUrl);

    httpPost.addHeader(CookieManager.cookieHeader());
    String param = "username=" + encode(UserConfig.username) + "&password=" + encode(UserConfig.password) + "&appid=otn";
    httpPost.setEntity(new StringEntity(param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
        result = EntityUtils.toString(response.getEntity());
        CookieManager.touch(response);
        ResultManager.touch(result, new ResultKey("uamtk", "uamtk"));
    } catch (IOException e) {
        logger.error("login error", e);
    }

    return result;
}
项目:Thrush    文件:HttpRequest.java   
public static String uamtk() {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.uamtk);

    httpPost.addHeader(CookieManager.cookieHeader());
    httpPost.setEntity(new StringEntity("appid=otn", ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        result = EntityUtils.toString(response.getEntity());
        CookieManager.touch(response);
        ResultManager.touch(result, new ResultKey("tk", "newapptk"));
    } catch (IOException e) {
        logger.error("uamtk error", e);
    }

    return result;
}
项目:integration-test-helper    文件:AomHttpClient.java   
/**
 * Updates the module
 *
 * @param moduleName
 *        the name of the module to add
 * @param objectToUpdate
 *        JSON containing the key/value pais to use for update
 * @return request object to check status codes and return values
 */
public Response updateModule( String moduleName, JSONObject objectToUpdate )
{
    HttpPut request = new HttpPut( this.yambasBase + "modules/" + moduleName );
    setAuthorizationHeader( request );
    request.addHeader( "x-apiomat-system", this.system.toString( ) );
    request.setEntity( new StringEntity( objectToUpdate.toString( ), ContentType.APPLICATION_JSON ) );

    try
    {
        final HttpResponse response = this.client.execute( request );
        return new Response( response );
    }
    catch ( final IOException e )
    {
        e.printStackTrace( );
    }
    return null;
}
项目:Thrush    文件:HttpRequest.java   
public static String checkOrderInfo(TrainQuery query) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo);

    httpPost.addHeader(CookieManager.cookieHeader());

    httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        logger.error("checkUser error", e);
    }

    return result;
}
项目:opentest    文件:HttpRequest.java   
public void setContent(String content, String contentType) {
    if (content == null) {
        content = "";
    }

    //TODO: Improve the validation logic
    if (contentType.indexOf('/') <= 0) {
        throw new RuntimeException(String.format("Content type \"%s\" is not a valid MIME type", contentType));
    }

    if (HttpEntityEnclosingRequestBase.class.isInstance(httpRequest)) {
        try {
            StringEntity requestEntity = new StringEntity(content);
            ((HttpEntityEnclosingRequestBase) this.httpRequest).setEntity(requestEntity);
            this.httpRequest.setHeader("Content-Type", contentType);
        } catch (Exception ex) {
            throw new RuntimeException("Failed to set HTTP request content", ex);
        }
    }
}
项目:daelic    文件:DruidClient.java   
private <REQ, RESP> RESP query(REQ request, Class<RESP> clazz) throws IOException, DruidException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(configuration.getUrl());

    StringEntity entity = new StringEntity(mapper.writeValueAsString(request), configuration.getCharset());
    httpPost.setEntity(entity);
    httpPost.setHeader("Content-type", "application/json");

    CloseableHttpResponse response = client.execute(httpPost);
    String content = EntityUtils.toString(response.getEntity(), configuration.getCharset());

    try {
        return mapper.readValue(content, clazz);
    } catch (Exception ex) {
        throw new DruidException(content);
    } finally {
        client.close();
    }
}
项目:weixinpay    文件:HttpUtil.java   
public static String postUrl(String url, String body) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

    //请求超时 ,连接超时
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    //读取超时
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);


    try {
        StringEntity entity = new StringEntity(body, "UTF-8");
        httppost.setEntity(entity);

        System.out.println(entity.toString());

        HttpResponse response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String charsetName = EntityUtils.getContentCharSet(response.getEntity());
            //System.out.println(charsetName + "<<<<<<<<<<<<<<<<<");

            String rs = EntityUtils.toString(response.getEntity());
            //System.out.println( ">>>>>>" + rs);

            return rs;
        } else {
            //System.out.println("Eorr occus");
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return "";
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException {

        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        String  body = "{\"default-user\": \""+usr+"\"}";

        HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default");
        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);
        }
    }
项目:QuickHttp    文件:QuickHttpController.java   
private void setupBodyContentFormEntity(HttpPost httpPost){
    if(isDebug){
        log("Request content: "+mBodyContent);
    }
    StringEntity entity = new StringEntity(mBodyContent,mContentType);
    httpPost.setEntity(entity);
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException
{
    try {           
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(
                new AuthScope(host, 8002),
                new UsernamePasswordCredentials("admin", "admin"));

            HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json");
            put.addHeader("Content-type", "application/json");
            put.setEntity(new StringEntity(jnode.toString()));

            HttpResponse response = client.execute(put);
            HttpEntity respEntity = response.getEntity();
            if(respEntity != null){
                String content =  EntityUtils.toString(respEntity);
                System.out.println(content);
            }
        }catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}
项目:restheart-java-client    文件:HttpConnectionUtils.java   
@Override
public <REQ> CloseableHttpResponse sendHttpPut(String url, REQ request) {
    CloseableHttpResponse execute = null;
    String requestJson = GsonUtils.toJson(request);

    try {
        LOGGER.log(Level.FINER, "Send PUT request:" + requestJson + " to url-" + url);
        HttpPut httpPut = new HttpPut(url);
        StringEntity entity = new StringEntity(requestJson, "UTF-8");
        entity.setContentType("application/json");
        httpPut.setEntity(entity);
        execute = this.httpClientFactory.getHttpClient().execute(httpPut);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Was unable to send PUT request:" + requestJson
            + " (displaying first 1000 chars) from url-" + url, e);
    }

    return execute;
}
项目:elasticjob-oray-client    文件:HttpUtils.java   
/**
 * Post String
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  String body)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
}
项目:Wechat-Group    文件:MaterialNewsInfoRequestExecutor.java   
@Override
public WxMpMaterialNews execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  Map<String, String> params = new HashMap<>();
  params.put("media_id", materialId);
  httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params)));
  try(CloseableHttpResponse response = httpclient.execute(httpPost)){
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    } else {
      return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class);
    }
  }finally {
    httpPost.releaseConnection();
  }

}
项目:teamcity-msteams-notifier    文件:MsTeamsNotificationTest.java   
@Test
public void post_whenResponseIsFailure_logsException() throws IOException {
    ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class);
    HttpClient httpClient = mock(HttpClient.class);
    BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, ""));
    response.setEntity(new StringEntity("failure reason here"));

    when(httpClient.execute(requestCaptor.capture())).thenReturn(response);

    MsTeamsNotification w = factory.getMsTeamsNotification(httpClient);

    MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent();
    content.setBuildDescriptionWithLinkSyntax("http://foo");
    content.setCommits(new ArrayList<Commit>());

    w.setPayload(content);
    w.setEnabled(true);
    w.post();

    assertNotNull(w.getResponse());
    assertFalse(w.getResponse().getOk());
}
项目:elasticsearch_my    文件:Netty4HeadBodyIsEmptyIT.java   
public void testTemplateExists() throws IOException {
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();
        {
            builder.array("index_patterns", "*");
            builder.startObject("settings");
            {
                builder.field("number_of_replicas", 0);
            }
            builder.endObject();
        }
        builder.endObject();

        client().performRequest("PUT", "/_template/template", emptyMap(),
            new StringEntity(builder.string(), ContentType.APPLICATION_JSON));
        headTestCase("/_template/template", emptyMap(), greaterThan(0));
    }
}
项目:elasticsearch_my    文件:RestHighLevelClientTests.java   
public void testPerformRequestOnResponseExceptionWithBrokenEntity2() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Unable to parse response body", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class));
}
项目:elasticsearch_my    文件:RestClientSingleHostIntegTests.java   
private Response bodyTest(final RestClient restClient, final String method) throws IOException {
    String requestBody = "{ \"field\": \"value\" }";
    StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
    int statusCode = randomStatusCode(getRandom());
    Response esResponse;
    try {
        esResponse = restClient.performRequest(method, "/" + statusCode, Collections.<String, String>emptyMap(), entity);
    } catch(ResponseException e) {
        esResponse = e.getResponse();
    }
    assertEquals(method, esResponse.getRequestLine().getMethod());
    assertEquals(statusCode, esResponse.getStatusLine().getStatusCode());
    assertEquals(pathPrefix + "/" + statusCode, esResponse.getRequestLine().getUri());
    assertEquals(requestBody, EntityUtils.toString(esResponse.getEntity()));

    return esResponse;
}
项目:elasticsearch-queryexpansion-plugin    文件:AbstractITCase.java   
/**
 * Creates the specified index in ElasticSearch
 * 
 * @param indexName
 *            the index name to augment
 * @param typeName
 *            the type name to augment
 * @param id
 *            the id of the document to add
 * @param jsonDocument
 *            the String JSON document to add
 */
protected static void createIndex(String indexName) {
    try {
        // Create our expand / search indices
        String endpoint = String.format("/%s", indexName);
        Map<String, String> params = new HashMap<String, String>();
        StringEntity requestBody = new StringEntity(INDEX_JSON);

        Response resp = client.performRequest("PUT", endpoint, params, requestBody, contentTypeHeader);
        staticLogger.debug("Response: " + resp.getStatusLine());

    } catch (IOException e) {
        // Ignore this...? probably already exists
        staticLogger.error(e.getMessage(), e);

        if (e instanceof UnsupportedEncodingException) {
            staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
            return;
        }
    }
}
项目:smarti    文件:RocketChatEndpoint.java   
private void notifyRocketChat(String callbackUrl, Conversation conversation, String token) {
    if (StringUtils.isBlank(callbackUrl)) return;

    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        final HttpPost post = new HttpPost(callbackUrl);
        final MultiValueMap<String, String> props = CollectionUtils.toMultiValueMap(conversation.getMeta().getProperties());
        post.setEntity(new StringEntity(
                toJsonString(new SmartiUpdatePing(conversation.getId(), props.getFirst(ConversationMeta.PROP_CHANNEL_ID), token)),
                ContentType.APPLICATION_JSON
        ));
        httpClient.execute(post, response -> null);
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage(), e);
        } else {
            log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage());
        }
    }
}
项目:wechat-api-java    文件:HttpRequestUtil.java   
public static String doPost(String url, String json) throws Exception {
    try {
        CloseableHttpClient client = getHttpClient(url);
        HttpPost post = new HttpPost(url);
        config(post);
        logger.info("====> Executing request: " + post.getRequestLine());
        if (!StringUtils.isEmpty(json)) {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        String responseBody = client.execute(post, getStringResponseHandler());
        logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody);
        return responseBody;
    } catch (Exception e) {
        if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
            throw new ConnectException("====> 连接服务器" + url + "失败: " + e.getMessage());
        }
        logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e);
    }
    return null;
}
项目:xrd4j    文件:PostClient.java   
/**
 * Builds a new HTTP POST request with the given URL and request body.
 * Content type of the request is set according to the given headers. If the
 * given headers do not contain Content-Type header, "application/xml" is
 * used.
 *
 * @param url URL where the request is sent
 * @param requestBody request body
 * @param headers HTTP headers to be added to the request
 * @return new HttpUriRequest object
 */
@Override
protected HttpUriRequest buildtHttpRequest(String url, String requestBody, Map<String, String> headers) {
    LOGGER.debug("Build new HTTP POST request.");
    HttpUriRequest request;
    // Create request entity that's used as request body
    StringEntity requestEntity = super.buildRequestEntity(requestBody, headers);
    if (requestEntity != null) {
        request = RequestBuilder.post().setUri(url).setEntity(requestEntity).build();
    } else {
        LOGGER.debug("No request body found for HTTP POST request.");
        request = RequestBuilder.post().setUri(url).build();
    }
    // Return request
    return request;
}
项目:CSipSimple    文件:Sipgate.java   
/**
 * {@inheritDoc}
 */
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "https://samurai.sipgate.net/RPC2";
    HttpPost httpPost = new HttpPost(requestURL);
    // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
    String userpassword = acc.username + ":" + acc.data;
    String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
    httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";

    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
项目:CSipSimple    文件:Mobex.java   
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "http://200.152.124.172/billing/webservice/Server.php";

    HttpPost httpPost = new HttpPost(requestURL);
    httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
            "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
            "<chave xsi:type=\"xsd:string\">" +
            acc.data +
            "</chave><username xsi:type=\"xsd:string\">" +
            acc.username.replaceAll("^12", "") +
            "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
项目:Wechat-Group    文件:WxMpPayServiceImpl.java   
private String executeRequest(String url, String requestStr) throws WxErrorException {
  HttpPost httpPost = new HttpPost(url);
  if (this.wxMpService.getHttpProxy() != null) {
    httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
  }

  try (CloseableHttpClient httpclient = HttpClients.custom().build()) {
    httpPost.setEntity(new StringEntity(new String(requestStr.getBytes("UTF-8"), "ISO-8859-1")));

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
      this.log.debug("\n[URL]:  {}\n[PARAMS]: {}\n[RESPONSE]: {}", url, requestStr, result);
      return result;
    }
  } catch (IOException e) {
    this.log.error("\n[URL]:  {}\n[PARAMS]: {}\n[EXCEPTION]: {}", url, requestStr, e.getMessage());
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg(e.getMessage()).build(), e);
  } finally {
    httpPost.releaseConnection();
  }
}
项目:hustic    文件:SearchRequest.java   
public SearchResponse execute() {
    final HttpClient client = wrapper.getHttpClient();

    SearchResponse searchResponse = null;
    try {
        final HttpPost httpPost = new HttpPost(uri);
        if (searchJson != null) {
            httpPost.setEntity(new StringEntity(searchJson.toString(),
                    ContentType.APPLICATION_JSON));
        }
        searchResponse = client.execute(httpPost, new SearchResponseHandler());
    } catch (Exception ex) {
        //Handle exception
    }

    return searchResponse;
}
项目:hustic    文件:IndexRequest.java   
public IndexResponse execute() {
    final HttpClient client = wrapper.getHttpClient();
    IndexResponse indexResponse = null;
    try {
        final HttpPut httpPut = new HttpPut(this.path);
        httpPut.setEntity(new StringEntity(this.data.toString(),
                ContentType.APPLICATION_JSON));

        System.out.println(this.data.toString());

        indexResponse = client.execute(httpPut, new IndexResponseHandler());
    } catch (IOException ioe) {
        //TODO: Tham
    }

    return indexResponse;
}
项目:marklogic-rdf4j    文件:ConnectedRESTQA.java   
public static void associateRESTServerWithDefaultUser(String restServerName,String userName,String authType)throws Exception{
    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(
            new AuthScope(host, 8002),
            new UsernamePasswordCredentials("admin", "admin"));
    String  body = "{ \"default-user\":\""+userName+"\",\"authentication\": \""+authType+"\",\"group-name\": \"Default\"}";

    HttpPut put = new HttpPut("http://"+host+":8002/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);
    }
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_string_response_since_httpClient_execute_returned_with_success()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertEquals(response, succResponse);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
项目:raven    文件:IOSCustomizedcast.java   
public String uploadContents(String contents) throws Exception {
    if (!rootJson.has("appkey") || !rootJson.has("timestamp") || !rootJson.has("validation_token")) {
        throw new Exception("appkey, timestamp and validation_token needs to be set.");
    }
    // Construct the json string
    JSONObject uploadJson = new JSONObject();
    uploadJson.put("appkey", rootJson.getString("appkey"));
    uploadJson.put("timestamp", rootJson.getString("timestamp"));
    uploadJson.put("validation_token", rootJson.getString("validation_token"));
    uploadJson.put("content", contents);
    // Construct the request
    String url = host + uploadPath;
    HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", USER_AGENT);
    StringEntity se = new StringEntity(uploadJson.toString(), "UTF-8");
    post.setEntity(se);
    // Send the post request and get the response
    HttpResponse response = client.execute(post);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    System.out.println(result.toString());
    // Decode response string and get file_id from it
    JSONObject respJson = new JSONObject(result.toString());
    String ret = respJson.getString("ret");
    if (!ret.equals("SUCCESS")) {
        throw new Exception("Failed to upload file");
    }
    JSONObject data = respJson.getJSONObject("data");
    String fileId = data.getString("file_id");
    // Set file_id into rootJson using setPredefinedKeyValue
    setPredefinedKeyValue("file_id", fileId);
    return fileId;
}
项目:fpm    文件:MetalinkDownloader.java   
private String getToken() throws IOException {
    HttpPost tokenRequest = new HttpPost("https://edelivery-ad.tomtom.com/automaticdownload/login");
    tokenRequest.setEntity(new StringEntity("user=" + login + "&password=" + password));
    log.info("Getting token");
    try (InputStream content = client.execute(tokenRequest).getEntity().getContent()) {
        return IOUtils.toString(content, "UTF-8");
    }
}