Java Code Examples for org.apache.http.client.methods.HttpPost#releaseConnection()

The following examples show how to use org.apache.http.client.methods.HttpPost#releaseConnection() . 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: KylinClient.java    From kylin with Apache License 2.0 7 votes vote down vote up
@Override
public void connect() throws IOException {
    HttpPost post = new HttpPost(baseUrl() + "/kylin/api/user/authentication");
    addHttpHeaders(post);
    StringEntity requestEntity = new StringEntity("{}", ContentType.create("application/json", "UTF-8"));
    post.setEntity(requestEntity);

    try {
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
            throw asIOException(post, response);
        }
    } finally {
        post.releaseConnection();
    }
}
 
Example 2
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 7 votes vote down vote up
private void doAddFormBook(String address, String resourceName, int status) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(address);

    String ct = "multipart/form-data; boundary=bqJky99mlBWa-ZuqjC53mG6EzbmlxB";
    post.setHeader("Content-Type", ct);
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/" + resourceName);
    post.setEntity(new InputStreamEntity(is));

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(status, response.getStatusLine().getStatusCode());
        if (status == 200) {
            InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
            assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                         stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
        }
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example 3
Source File: HttpClientPool.java    From message_interface with MIT License 7 votes vote down vote up
public String uploadFile(String url, String path) throws IOException {
    HttpPost post = new HttpPost(url);
    try {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        FileBody fileBody = new FileBody(new File(path)); //image should be a String
        builder.addPart("file", fileBody);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        return readResponse(response);
    } finally {
        post.releaseConnection();
    }
}
 
Example 4
Source File: MaterialVideoInfoApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).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 = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent, WxType.MP);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    } else {
      return WxMpMaterialVideoInfoResult.fromJson(responseContent);
    }
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 5
Source File: DefaultRestClient.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public HttpResponse doPost(String resourcePath, Object payload) throws RestClientException {

        HttpPost post = new HttpPost(resourcePath);
        addPayloadJsonString(payload, post);
        setAuthHeader(post);
        try {
            return httpClient.execute(post);

        } catch (IOException e) {
            String errorMsg = "Error while executing POST statement";
            log.error(errorMsg, e);
            throw new RestClientException(errorMsg, e);
        } finally {
            post.releaseConnection();
        }
    }
 
Example 6
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void doAddBook(String type, String address, InputStream is, int status) throws Exception {

        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(address);

        String ct = type + "; type=\"text/xml\"; " + "start=\"rootPart\"; "
            + "boundary=\"----=_Part_4_701508.1145579811786\"";
        post.setHeader("Content-Type", ct);

        post.setEntity(new InputStreamEntity(is));

        try {
            CloseableHttpResponse response = client.execute(post);
            assertEquals(status, response.getStatusLine().getStatusCode());
            if (status == 200) {
                InputStream expected = getClass().getResourceAsStream("resources/expected_add_book.txt");
                assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                             stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
            }
        } finally {
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    }
 
Example 7
Source File: PreviewDeployerImpl.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
protected boolean doDeleteTarget(String site, String environment) {
    boolean toReturn = true;
    String requestUrl = getDeleteTargetUrl(site, environment);

    HttpPost postRequest = new HttpPost(requestUrl);

    try {
        CloseableHttpResponse response = httpClient.execute(postRequest);
        if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) {
            toReturn = false;
        }
    } catch (IOException e) {
        logger.error("Error while sending delete preview target request for site " + site, e);
        toReturn = false;
    } finally {
        postRequest.releaseConnection();
    }
    return toReturn;
}
 
Example 8
Source File: JAXRSClientServerSpringBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void doPost(String endpointAddress, int expectedStatus, String contentType,
                    String inResource, String expectedResource) throws Exception {

    File input = new File(getClass().getResource(inResource).toURI());
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(endpointAddress);
    post.setHeader("Content-Type", contentType);
    post.setEntity(new FileEntity(input, ContentType.TEXT_XML));

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(expectedStatus, response.getStatusLine().getStatusCode());

        if (expectedStatus != 400) {
            InputStream expected = getClass().getResourceAsStream(expectedResource);
            assertEquals(stripXmlInstructionIfNeeded(getStringFromInputStream(expected)),
                         stripXmlInstructionIfNeeded(EntityUtils.toString(response.getEntity())));
        } else {
            assertTrue(EntityUtils.toString(response.getEntity())
                           .contains("Cannot find the declaration of element"));
        }
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example 9
Source File: MaterialDeleteApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean execute(String uri, String materialId) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).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 = requestHttp.getRequestHttpClient().execute(httpPost)) {
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    WxError error = WxError.fromJson(responseContent, WxType.MP);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    } else {
      return true;
    }
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 10
Source File: JAXRSAtomBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Entry addEntry(String endpointAddress) throws Exception {
    Entry e = createBookEntry(256, "AtomBook");
    StringWriter w = new StringWriter();
    e.writeTo(w);

    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(endpointAddress);
    post.setEntity(new StringEntity(w.toString(), ContentType.APPLICATION_ATOM_XML));

    String location = null;
    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(201, response.getStatusLine().getStatusCode());
        location = response.getFirstHeader("Location").getValue();
        InputStream ins = response.getEntity().getContent();
        Document<Entry> entryDoc = abdera.getParser().parse(copyIn(ins));
        assertEquals(entryDoc.getRoot().toString(), e.toString());
    } finally {
        post.releaseConnection();
    }

    Entry entry = getEntry(location, null);
    assertEquals(location, entry.getBaseUri().toString());
    assertEquals("AtomBook", entry.getTitle());
    return entry;
}
 
Example 11
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsumeTypeMismatch() throws Exception {
    String endpointAddress =
        "http://localhost:" + PORT + "/bookstore/unsupportedcontenttype";

    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(endpointAddress);
    post.addHeader("Content-Type", "application/bar");
    post.addHeader("Accept", "text/xml");

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(415, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example 12
Source File: KylinClient.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public void connect() throws IOException {
    HttpPost post = new HttpPost(baseUrl() + "/kylin/api/user/authentication");
    addHttpHeaders(post);
    StringEntity requestEntity = new StringEntity("{}", ContentType.create("application/json", "UTF-8"));
    post.setEntity(requestEntity);

    try {
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
            throw asIOException(post, response);
        }
    } finally {
        post.releaseConnection();
    }
}
 
Example 13
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Send an exported archive over to this hop server
 *
 * @param filename The archive to send
 * @param type     The type of file to add to the hop server (AddExportServlet.TYPE_*)
 * @param load     The filename to load in the archive (the .hwf or .hpl)
 * @return the XML of the web result
 * @throws Exception in case something goes awry
 */
public String sendExport( String filename, String type, String load ) throws Exception {
  // Request content will be retrieved directly from the input stream
  try ( InputStream is = HopVfs.getInputStream( HopVfs.getFileObject( filename ) ) ) {
    // Execute request
    HttpPost method = buildSendExportMethod( type, load, is );
    try {
      return executeAuth( method );
    } finally {
      // Release current connection to the connection pool once you are done
      method.releaseConnection();
      if ( log.isDetailed() ) {
        log.logDetailed( BaseMessages.getString( PKG, "HopServer.DETAILED_SentExportToService",
          RegisterPackageServlet.CONTEXT_PATH, environmentSubstitute( hostname ) ) );
      }
    }
  }
}
 
Example 14
Source File: SlaveServer.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Send an exported archive over to this slave server
 *
 * @param filename The archive to send
 * @param type     The type of file to add to the slave server (AddExportServlet.TYPE_*)
 * @param load     The filename to load in the archive (the .kjb or .ktr)
 * @return the XML of the web result
 * @throws Exception in case something goes awry
 */
public String sendExport( String filename, String type, String load ) throws Exception {
  // Request content will be retrieved directly from the input stream
  try ( InputStream is = KettleVFS.getInputStream( KettleVFS.getFileObject( filename ) ) ) {
    // Execute request
    HttpPost method = buildSendExportMethod( type, load, is );
    try {
      return executeAuth( method );
    } finally {
      // Release current connection to the connection pool once you are done
      method.releaseConnection();
      if ( log.isDetailed() ) {
        log.logDetailed( BaseMessages.getString( PKG, "SlaveServer.DETAILED_SentExportToService",
            RegisterPackageServlet.CONTEXT_PATH, environmentSubstitute( hostname ) ) );
      }
    }
  }
}
 
Example 15
Source File: KylinClient.java    From kylin with Apache License 2.0 5 votes vote down vote up
private SQLResponseStub executeKylinQuery(String sql, List<StatementParameter> params,
        Map<String, String> queryToggles) throws IOException {
    String url = baseUrl() + "/kylin/api/query";
    String project = connInfo.getProject();

    PreparedQueryRequest request = new PreparedQueryRequest();
    if (null != params) {
        request.setParams(params);
    }
    request.setSql(sql);
    request.setProject(project);
    request.setBackdoorToggles(queryToggles);

    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    String postBody = jsonMapper.writeValueAsString(request);
    logger.debug("Post body:\n {}", postBody);
    StringEntity requestEntity = new StringEntity(postBody, ContentType.create("application/json", "UTF-8"));
    post.setEntity(requestEntity);

    try {
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
            throw asIOException(post, response);
        }

        SQLResponseStub stub = jsonMapper.readValue(response.getEntity().getContent(), SQLResponseStub.class);
        return stub;
    } finally {
        post.releaseConnection();
    }
}
 
Example 16
Source File: SaltApiNodeStepPlugin.java    From salt-step with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Authenticates the given username/password with the given eauth system
 * against the salt-api endpoint
 * 
 * @param capability
 *            The {@link SaltApiCapability} that describes the supported features of the saltEndpoint 
 * @param user
 *            The user to auth with
 * @param password
 *            The password for the given user
 * @return X-Auth-Token for use in subsequent requests
 */
protected String authenticate(final SaltApiCapability capability, HttpClient client, String user, String password) throws IOException, HttpException,
        InterruptedException {
    List<NameValuePair> params = Lists.newArrayListWithCapacity(3);
    params.add(new BasicNameValuePair(SALT_API_USERNAME_PARAM_NAME, user));
    params.add(new BasicNameValuePair(SALT_API_PASSWORD_PARAM_NAME, password));
    params.add(new BasicNameValuePair(SALT_API_EAUTH_PARAM_NAME, eAuth));
    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params, CHAR_SET_ENCODING);
    postEntity.setContentEncoding(CHAR_SET_ENCODING);
    postEntity.setContentType(REQUEST_CONTENT_TYPE);

    HttpPost post = httpFactory.createHttpPost(saltEndpoint + LOGIN_RESOURCE);
    post.setEntity(postEntity);
    
    logWrapper.info("Authenticating with salt-api endpoint: [%s]", post.getURI());
    HttpResponse response = retryExecutor.execute(logWrapper, client, post, numRetries, new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return input != capability.getLoginFailureResponseCode();
        }
    });

    try {
        int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == capability.getLoginSuccessResponseCode()) {
            return response.getHeaders(SALT_AUTH_TOKEN_HEADER)[0].getValue();
        } else if (responseCode == capability.getLoginFailureResponseCode()) {
            return null;
        } else {
            throw new HttpException(String.format("Unexpected failure interacting with salt-api %s", response
                    .getStatusLine().toString()));
        }
    } finally {
        closeResource(response.getEntity());
        post.releaseConnection();
    }
}
 
Example 17
Source File: MaterialVoiceAndImageDownloadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream execute(String uri, String materialId) throws WxErrorException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (requestHttp.getRequestHttpProxy() != null) {
    RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).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 = requestHttp.getRequestHttpClient().execute(httpPost);
       InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response)) {
    // 下载媒体文件出错
    byte[] responseContent = IOUtils.toByteArray(inputStream);
    String responseContentString = new String(responseContent, StandardCharsets.UTF_8);
    if (responseContentString.length() < 100) {
      try {
        WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class);
        if (wxError.getErrorCode() != 0) {
          throw new WxErrorException(wxError);
        }
      } catch (com.google.gson.JsonSyntaxException ex) {
        return new ByteArrayInputStream(responseContent);
      }
    }
    return new ByteArrayInputStream(responseContent);
  } finally {
    httpPost.releaseConnection();
  }
}
 
Example 18
Source File: HttpUtil.java    From codehelper.generator with Apache License 2.0 5 votes vote down vote up
/**
 * 发送xml的post请求 指定contentType 和Charset
 *
 * @param url
 * @param xml
 * @param headers
 * @return
 */
@Nullable
public static String postXML(String url, String xml, ContentType contentType,final Charset charset,  Header... headers) {
    CloseableHttpClient client = getHttpclient();
    HttpPost httpPost = new HttpPost(url);
    long start = System.currentTimeMillis();
    try {
        HttpEntity httpEntity = new StringEntity(xml,contentType);
        if (headers != null && headers.length > 0) {
            for (Header header : headers) {
                httpPost.addHeader(header);
            }
        }
        httpPost.setEntity(httpEntity);
        CloseableHttpResponse response = client.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity, charset);
        }
    } catch (Exception e) {
        logger.error("push xml fail,url:{}", url, e);
    } finally {
        long cost = System.currentTimeMillis() - start;
        logger.info("httpUtil_postXml {}", cost);
        httpPost.releaseConnection();
    }
    return null;
}
 
Example 19
Source File: HttpClientUtil.java    From hermes with Apache License 2.0 5 votes vote down vote up
/**
 * https post请求
 * @param url
 * @param formParamMap
 * @return
 */
public static String doPostHttps(String url,Map<String, String> formParamMap) throws  Exception {
	initSSLContext();
	HttpPost post = new HttpPost(url);
	StringBuilder stringBuilder = new StringBuilder();
	List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
	if(formParamMap !=null){
		for(Map.Entry<String, String> entity: formParamMap.entrySet()){
			nameValuePairList.add(new BasicNameValuePair(entity.getKey(), entity.getValue())) ;
		}
	}
	post.setEntity(new UrlEncodedFormEntity(nameValuePairList, HermesConstants.CHARSET_UTF8));
	HttpResponse  response = httpClient.execute(post);
	HttpEntity respEntity = response.getEntity();
	int  responseCode = response.getStatusLine().getStatusCode();
	Logger.info("httpClient post 响应状态responseCode="+responseCode+", 请求 URL="+url);
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(respEntity.getContent(), "UTF-8"));
	String text = null;
	if(responseCode == RSP_200 || responseCode == RSP_400){
		while ((text = bufferedReader.readLine()) != null) {
			stringBuilder.append(text);
		}
	}else{
	    throw new Exception("接口请求异常:接口响应状态="+responseCode);
	}
	bufferedReader.close();
	post.releaseConnection();
	return stringBuilder.toString();
}
 
Example 20
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Send a POST request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
 * supplied
 * @param content the content bytes
 * @return a Response object with response detail
 * @throws IOException
 */
public Response post(Cluster cluster, String path, Header[] headers,
    byte[] content) throws IOException {
  HttpPost method = new HttpPost(path);
  try {
    method.setEntity(new InputStreamEntity(new ByteArrayInputStream(content), content.length));
    HttpResponse resp = execute(cluster, method, headers, path);
    headers = resp.getAllHeaders();
    content = getResponseBody(resp);
    return new Response(resp.getStatusLine().getStatusCode(), headers, content);
  } finally {
    method.releaseConnection();
  }
}