org.apache.http.client.methods.HttpPost Java Examples

The following examples show how to use org.apache.http.client.methods.HttpPost. 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: 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 #2
Source File: ParameterCharacterEncodingTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipartCharacterEncoding() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        String message = "abcčšž";
        String charset = "UTF-8";

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext");

        MultipartEntity multipart = new MultipartEntity();
        multipart.addPart("charset", new StringBody(charset, Charset.forName(charset)));
        multipart.addPart("message", new StringBody(message, Charset.forName(charset)));
        post.setEntity(multipart);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals(message, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #3
Source File: JsonHttpProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
private <T> T requestResponse(String url, Object request, Class<T> responseClass) {
	HttpPost post = new HttpPost(url);
	try {
		post.setEntity(new StringEntity(gson.toJson(request), ContentType.APPLICATION_JSON));

		HttpResponse response = httpClient.execute(httpHost, post);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) {
			throw new RuntimeIOException("Unexpected response code: " + status);
		}

		return gson.fromJson(EntityUtils.toString(response.getEntity()), responseClass);
	} catch (IOException e) {
		throw new RuntimeIOException("HTTP error: " + e, e);
	}
}
 
Example #4
Source File: JenkinsHttpClient.java    From verigreen with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a POST request of XML (instead of using json mapper) and return a string rendering of
 * the response entity.
 * 
 * @param path
 *            path to request, can be relative or absolute
 * @param XML
 *            data data to post
 * @return A string containing the xml response (if present)
 * @throws IOException
 *             , HttpResponseException
 */
public String post_xml(String path, String xml_data) throws IOException, HttpResponseException {
    HttpPost request = new HttpPost(api(path));
    if (xml_data != null) {
        request.setEntity(new StringEntity(xml_data, ContentType.APPLICATION_XML));
    }
    HttpResponse response = client.execute(request, localContext);
    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status >= 300) {
        throw new HttpResponseException(status, response.getStatusLine().getReasonPhrase());
    }
    try {
        InputStream content = response.getEntity().getContent();
        Scanner s = new Scanner(content, CHARSET_UTF_8);
        StringBuffer sb = new StringBuffer();
        while (s.hasNext()) {
            sb.append(s.next());
        }
        return sb.toString();
    } finally {
        EntityUtils.consume(response.getEntity());
    }
}
 
Example #5
Source File: Session.java    From timer with Apache License 2.0 6 votes vote down vote up
public Session process() throws IOException {

        HttpRequest request = this.getRequest();
        Objects.requireNonNull(this.request);
        HttpClient httpClient = this.getHttpClient();
        HttpClientContext context = this.getContext();
        if (request instanceof HttpGet) {
            this.getContext().setCookieStore(cookies);
            HttpGet get = (HttpGet) request;
            this.httpResponse = httpClient.execute(get, context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        } else if (this.request instanceof HttpPost) {
            context.setCookieStore(cookies);
            HttpPost post = (HttpPost) request;
            post.setEntity(this.getProviderService().builder());
            this.httpResponse = this.httpClient.execute(post, this.context);
            this.httpCode = httpResponse.getStatusLine().getStatusCode();
            this.repUtils = new ResponseUtils(this.httpResponse);
        }
        return this;
    }
 
Example #6
Source File: CxfWsCdiSecureExampleTest.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void greetClientCert() throws Exception {
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(createTrustedClientCertSocketFactory(WILDFLY_HOME)).build()) {
        HttpPost request = new HttpPost(CXF_ENDPOINT_URI);
        request.setHeader("Content-Type", "text/xml");
        request.setHeader("soapaction", "\"urn:greet\"");

        request.setEntity(
                new StringEntity(String.format(WS_MESSAGE_TEMPLATE, "Hi", "Joe"), StandardCharsets.UTF_8));
        try (CloseableHttpResponse response = httpclient.execute(request)) {
            Assert.assertEquals(200, response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            Assert.assertTrue(body.contains("Hi Joe"));
        }
    }
}
 
Example #7
Source File: HttpUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
public static String sendJSONPost(String url, String jsonData, Map<String, String> headers) {
    String result = null;
    HttpPost httpPost = new HttpPost(url);
    StringEntity postEntity = new StringEntity(jsonData, CHARSET_NAME);
    postEntity.setContentType("application/json");
    httpPost.setEntity(postEntity);
    httpPost.setHeader("Content-Type", "application/json");
    HttpClient client = HttpClients.createDefault();
    if (headers != null && !headers.isEmpty()) {
        headers.forEach((k, v) -> {
            httpPost.setHeader(k, v);
        });
    }
    try {
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "UTF-8");
    } catch (Exception e) {
        logger.error("http request error ", e);
    } finally {
        httpPost.abort();
    }
    return result;
}
 
Example #8
Source File: HttpClientUtil.java    From octo-rpc with Apache License 2.0 6 votes vote down vote up
public static String doPost(String url, String paramStr, Map<String, String> headers) {
    try {
        HttpPost httppost = new HttpPost(url);
        StringEntity str = new StringEntity(paramStr, ContentType.APPLICATION_JSON);
        httppost.setEntity(str);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httppost.setHeader(header.getKey(), header.getValue());
            }
        }
        return httpclient.execute(httppost, getResponseHandler());
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return "";
}
 
Example #9
Source File: HttpService.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
/**
 * post访问
 * @param url 地址
 * @param body 访问数据
 * @param contentType 访问的格式
 * @return 访问返回值
 */
@Suspendable
public String doPost(String url, final String body, ContentType contentType){
    HttpPost post = new HttpPost(url);
    String str = "";
    try {
        StringEntity strEn = new StringEntity(body, contentType);
        post.setEntity(strEn);

        HttpResponse response = httpclient.execute(post);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instreams = entity.getContent();
            str = convertStreamToString(instreams);
            logger.info("get http post response:{}", str);
        }
    }catch (Exception e){
        logger.error("post exception:", e);
    }finally {
        post.abort();
    }
    return str;
}
 
Example #10
Source File: RtPlugins.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void pullAndInstall(final String remote, final String name,
                           final JsonArray properties)
    throws IOException, UnexpectedResponseException {
    final HttpPost pull =
        new HttpPost(
            new UncheckedUriBuilder(this.baseUri.toString().concat("/pull"))
                .addParameter("remote", remote)
                .addParameter("name", name)
                .build()
        );
    try {
        pull.setEntity(
            new StringEntity(properties.toString())
        );
        this.client.execute(
            pull,
            new MatchStatus(
                pull.getURI(),
                HttpStatus.SC_NO_CONTENT
            )
        );
    } finally {
        pull.releaseConnection();
    }
}
 
Example #11
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP POST 字节数组
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

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

    if (bodys != null) {
        post.setEntity(new ByteArrayEntity(bodys));
    }

    return convert(httpClient.execute(post));
}
 
Example #12
Source File: SessionService.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void openNetworkSession(String tempKey) {
    Log.d(TAG, "Opening network session: " + tempKey);
    if (!connected()) {
        Log.d(TAG, "openNetworkSession()..connected = false");
        openLocalSession(tempKey);
    } else {
        try {
            Log.d(TAG, "openNetworkSession()..connected = true");
            String[] credentials = tempSessions.get(tempKey);
            HttpPost post = MDSInterface2.createSessionRequest(this,
                    credentials[0], credentials[1]);
            Log.i(TAG, "openNetworkSession(...) " + post.getURI());
            new HttpTask<String>(new AuthListener(tempKey)).execute(post);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
        }
    }
}
 
Example #13
Source File: HttpQueryContext.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public byte[] doPost(String sessionId) {
//        FileEntity fe = new FileEntity();
//        StringEntity se = new StringEntity("","");
        try {
            FileBody fileBody = new FileBody(new File(""));
            StringBody stringBody = new StringBody("");
            HttpPost httpPost = new HttpPost("");
            MultipartEntityBuilder meb = MultipartEntityBuilder.create();
            meb.addPart("name", fileBody);
            meb.addPart("Sname",stringBody);
            HttpEntity httpEntity =  meb.build();
            httpPost.setEntity(httpEntity);
        }catch (Exception e){

        }
//        NameValuePair nameValuePair = new FileNa("","");
//        eb.setParameters()
//        HttpEntity httpEntity =  eb.build();
//        CloseableHttpPost httpPost = null;
//        httpPost.setEntity(httpEntity);
//        StringBody userName = new StringBody("Scott", ContentType.create(
//                                     "text/plain", Consts.UTF_8));
        return null;
    }
 
Example #14
Source File: HttpClientUtil.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * httpClient post 获取资源
 * @param url
 * @param params
 * @return
 */
public static String post(String url, Map<String, Object> params) {
	log.info(url);
	try {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);
		if (params != null && params.size() > 0) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				Object object = params.get(key);
				nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
		}
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity(), "UTF-8");
	} catch (Exception e) {
		log.error(e);
	}
	return null;
}
 
Example #15
Source File: AsuraCommonsHttpclient.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * @param url
 * @param params
 * @param header
 * @param connectTimeout
 * @param socketTimeout
 * @return
 * @throws IOException
 */
public String doPostForm(@NotNull String url, Map<String, String> params, Map<String, String> header, int connectTimeout, int socketTimeout) throws IOException {
    Objects.requireNonNull(url, "http url cannot be bull");
    /**
     * 默认的httpclient
     */
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    handlerHeader(header, httpPost);
    handlerRequestConfig(connectTimeout, socketTimeout, httpPost);
    handlerParam(params, httpPost);
    try {
        return httpClient.execute(httpPost, new StringResponseHandler());
    } finally {
        httpClient.close();
    }
}
 
Example #16
Source File: AuthenticationCommonsHttpInvokerRequestExecutor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Overridden to obtain the Credentials from the CredentialsSource and pass
 * them via HTTP BASIC Authorization.
 */

protected void setRequestBody(final HttpInvokerClientConfiguration config,
    final HttpPost httpPost, final ByteArrayOutputStream baos) throws IOException {
	final UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) this.credentialsSource.getCredentials(this.serviceConfiguration.getEndpointUrl().toExternalForm());

    final String base64 = credentials.getUsername() + ":"
    + credentials.getPassword();
    httpPost.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

    if (logger.isDebugEnabled()) {
        logger
            .debug("HttpInvocation now presenting via BASIC authentication CredentialsSource-derived: "
                + credentials.getUsername());
    }
    
    super.setRequestBody(config, httpPost, baos);
}
 
Example #17
Source File: GoogleAnalyticsDataPublisher.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Use this method to publish using POST.
 * @param payload - use the buildPayload method to retrieve NameValuePair to use as payload here.
 * @param userAgent - set the userAgent - this can be overridden if userAgentOverride (ua) is set in payload
 * @param useSSL - to publish using HTTPS, set this value to true.
 * @return
 */
public static boolean publishPOST(List<NameValuePair> payload, String userAgent, boolean useSSL) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(getURI(useSSL));
    post.setHeader(GoogleAnalyticsConstants.HTTP_HEADER_USER_AGENT, userAgent);

    try {
        post.setEntity(new UrlEncodedFormEntity(payload));
        HttpResponse response = client.execute(post);

        if((response.getStatusLine().getStatusCode() == 200)
                && (response.getFirstHeader(GoogleAnalyticsConstants.HTTP_HEADER_CONTENT_TYPE).getValue()
                .equals(GoogleAnalyticsConstants.RESPONSE_CONTENT_TYPE))) {
            return true;
        }
        return false;
    } catch (IOException e) {
        return false;
    }
}
 
Example #18
Source File: HttpClient.java    From jshERP with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 采用Post方式发送请求,获取响应数据
 *
 * @param url        url地址
 * @param param  参数值键值对的字符串
 * @return
 */
public static String httpPost(String url, String param) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        EntityBuilder builder = EntityBuilder.create();
        builder.setContentType(ContentType.APPLICATION_JSON);
        builder.setText(param);
        post.setEntity(builder.build());

        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        logger.info("状态:"+statusCode+"数据:"+data);
        return data;
    } catch(Exception e){
        throw new RuntimeException(e.getMessage());
    } finally {
        try{
            client.close();
        }catch(Exception ex){ }
    }
}
 
Example #19
Source File: HttpPostParams.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String base) throws Exception {
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	for (String key : params.keySet()) {
		String value = params.get(key);
		formparams.add(new BasicNameValuePair(key, value));
	}
	HttpPost request = new HttpPost(base);

       RequestConfig localConfig = RequestConfig.custom()
               .setCookieSpec(CookieSpecs.STANDARD)
               .build();
       request.setConfig(localConfig); 
	request.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
	request.setHeader("Content-Type", "application/x-www-form-urlencoded");		//内容为post
	return httpClient.execute(request);
}
 
Example #20
Source File: MDSInterface2.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static MDSResult doPost(String scheme, String host, int port,
                                  String path,
                                  List<NameValuePair> postData) throws UnsupportedEncodingException {
    URI uri = null;
    try {
        uri = URIUtils.createURI(scheme, host, port, path, null, null);
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw new IllegalArgumentException(String.format("Can not post to mds: %s, %s, %d, %s", scheme, host, port, path), e);
    }
    Log.d(TAG, "doPost() uri: " + uri.toASCIIString());
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
    post.setEntity(entity);
    return MDSInterface2.doExecute(post);

}
 
Example #21
Source File: HttpUtil.java    From roncoo-education with MIT License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param param
 * @return
 */
public static String postForPay(String url, Map<String, Object> param) {
	logger.info("POST 请求, url={},map={}", url, param.toString());
	try {
		HttpPost httpPost = new HttpPost(url.trim());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> entry : param.entrySet()) {
			nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
		}
		StringEntity se = new UrlEncodedFormEntity(nvps, CHARSET_UTF_8);
		httpPost.setEntity(se);
		HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost);
		return EntityUtils.toString(httpResponse.getEntity(), CHARSET_UTF_8);
	} catch (Exception e) {
		logger.info("HTTP请求出错", e);
		e.printStackTrace();
	}
	return "";
}
 
Example #22
Source File: MyRobot.java    From wakao-app with MIT License 6 votes vote down vote up
public String postDataToServer(List<NameValuePair> nvs, String url, String cookie) {
	DefaultHttpClient httpclient = new DefaultHttpClient();
	HttpPost httpost = new HttpPost(url);
	httpost.setHeader("Cookie", cookie);
	StringBuilder sb = new StringBuilder();
	// 设置表单提交编码为UTF-8
	try {
		httpost.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
		HttpResponse response = httpclient.execute(httpost);
		HttpEntity entity = response.getEntity();
		InputStreamReader isr = new InputStreamReader(entity.getContent());
		BufferedReader bufReader = new BufferedReader(isr);
		String lineText = null;
		while ((lineText = bufReader.readLine()) != null) {
			sb.append(lineText);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		httpclient.getConnectionManager().shutdown();
	}
	return sb.toString();
}
 
Example #23
Source File: Log.java    From DiscordBot with 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 #24
Source File: CapitalTradeOrderService.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
public String record(TransactionContext transactionContext, CapitalTradeOrderDto tradeOrderDto) {
    logger.info("CapitalTradeOrderService record method called.");
    logger.info("Transaction ID:" + transactionContext.getXid().toString());
    logger.info("Transaction status:" + transactionContext.getStatus());

    try {
        CapitalTradeOrderRecordRequest request = new CapitalTradeOrderRecordRequest();
        request.setTransactionContext(transactionContext);
        request.setCapitalTradeOrderDto(tradeOrderDto);
        HttpPost post = new HttpPost("http://127.0.0.1:7001/record");
        post.addHeader("Content-Type", "application/json");
        StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(request));
        post.setEntity(stringEntity);
        CloseableHttpResponse response = closeableHttpClient.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Capital trade order record request failed.");
        }
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: MaterialVoiceAndImageDownloadRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public InputStream execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, 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)));
  CloseableHttpResponse response = httpclient.execute(httpPost);
  // 下载媒体文件出错
  InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
  byte[] responseContent = IOUtils.toByteArray(inputStream);
  String responseContentString = new String(responseContent, "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);
}
 
Example #26
Source File: RouteExampleControllerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenRoute_whenPost_thenCorrectOutput() throws Exception {
    final HttpUriRequest request = new HttpPost("http://localhost:9000/route-example");
    try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
        .build()
        .execute(request);) {
        assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
    }
}
 
Example #27
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 #28
Source File: TaskCollectionResourceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test creating a task. POST runtime/tasks
 */
public void testCreateTaskNoBody() throws Exception {
    try {
        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_TASK_COLLECTION));
        httpPost.setEntity(null);
        closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}
 
Example #29
Source File: AppService.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void uploadAppDefinition(HttpServletResponse httpResponse, ServerConfig serverConfig, String name, byte[] bytes) throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, APP_IMPORT_AND_PUBLISH_URL));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);
    clientUtil.execute(post, httpResponse, serverConfig);
}
 
Example #30
Source File: PreparationAddAction.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private HttpRequestBase onExecute(String preparationId, List<AppendStep> steps) {
    try {
        final String stepAsString = objectMapper.writeValueAsString(steps);
        final InputStream stepInputStream = new ByteArrayInputStream(stepAsString.getBytes(StandardCharsets.UTF_8));

        final HttpPost actionAppend =
                new HttpPost(preparationServiceUrl + "/preparations/" + preparationId + "/actions");
        actionAppend.setHeader(new BasicHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE));
        actionAppend.setEntity(new InputStreamEntity(stepInputStream));

        return actionAppend;
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}