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

The following examples show how to use org.apache.http.client.methods.HttpPost. 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
@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 2
Source Project: PeonyFramwork   Source File: HttpService.java    License: 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 3
@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 4
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 5
Source Project: AsuraFramework   Source File: AsuraCommonsHttpclient.java    License: 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 6
Source Project: tcc-transaction   Source File: CapitalTradeOrderService.java    License: 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 7
Source Project: message_interface   Source File: HttpClientPool.java    License: MIT License 6 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 8
/**
 * 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 9
@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 10
/**
 * 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 11
Source Project: jshERP   Source File: HttpClient.java    License: 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 12
Source Project: SnowGraph   Source File: HttpPostParams.java    License: 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 13
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 14
Source Project: roncoo-education   Source File: HttpUtil.java    License: 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 15
Source Project: wakao-app   Source File: MyRobot.java    License: 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 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: mumu   Source File: HttpClientUtil.java    License: 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 18
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 19
Source Project: api-gateway-demo-sign-java   Source File: HttpUtil.java    License: 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 20
Source Project: timer   Source File: Session.java    License: 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 21
Source Project: diozero   Source File: JsonHttpProtocolHandler.java    License: 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 22
Source Project: verigreen   Source File: JenkinsHttpClient.java    License: 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 23
Source Project: common-project   Source File: HttpUtil.java    License: 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 24
Source Project: octo-rpc   Source File: HttpClientUtil.java    License: 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 25
Source Project: codehelper.generator   Source File: HttpUtil.java    License: 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 26
Source Project: p4ic4idea   Source File: BasicRequest.java    License: Apache License 2.0 5 votes vote down vote up
BasicResponse postJson(SwarmConfig config, String path, String body)
        throws IOException, UnauthorizedAccessException {
    final String url = toUrl(config, path, null);
    final HttpPost request = new HttpPost(url);
    final HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
    request.setEntity(entity);
    return request(config, request);
}
 
Example 27
Source Project: product-emm   Source File: HttpClientStackTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void createDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example 28
Source Project: clouddisk   Source File: FileExistParser.java    License: MIT License 5 votes vote down vote up
@Override
public HttpPost initRequest(final FileExistParameter parameter) {
	final HttpPost request = new HttpPost(getRequestUri());
	final List<NameValuePair> data = new ArrayList<>(0);
	data.add(new BasicNameValuePair(CONST.DIR_NAME, parameter.getDir()));
	data.addAll(parameter.getFnames().stream().map(fame -> new BasicNameValuePair(CONST.FNAME_NAME, fame)).collect(Collectors.toList()));
	data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL));
	request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8));
	return request;
}
 
Example 29
Source Project: data-prep   Source File: SuggestColumnActions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param input the column metadata to get the actions for (in json).
 */
private SuggestColumnActions(InputStream input) {
    super(GenericCommand.TRANSFORM_GROUP);
    execute(() -> {
        HttpPost post = new HttpPost(transformationServiceUrl + "/suggest/column");
        post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        post.setEntity(new InputStreamEntity(input));
        return post;
    });
    onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_RETRIEVE_SUGGESTED_ACTIONS, e));
    on(HttpStatus.NO_CONTENT, HttpStatus.ACCEPTED).then(asNull());
    on(HttpStatus.OK).then(pipeStream());
}
 
Example 30
Source Project: product-ei   Source File: ActivitiRestClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to claim task by a user
 *
 * @param taskID used to identify the task to be claimed
 * @return String Array containing status
 * @throws IOException
 */
public String claimTaskByTaskId(String taskID) throws IOException {
    String url = serviceURL + "runtime/tasks/" + taskID;
    DefaultHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    StringEntity params = new StringEntity("{\"action\" : \"claim\"," +
                                           "\"assignee\" :\"" + USER_CLAIM + "\"}",
                                           ContentType.APPLICATION_JSON);
    httpPost.setEntity(params);
    HttpResponse response = httpClient.execute(httpPost);
    return response.getStatusLine().toString();
}
 
Example 31
/**
 * Create Volume using JsonObjectBuilder.
 * @param json Json Object Builder object.
 * @return The created Volume.
 * @throws IOException If something goes wrong.
 */
private Volume createVolume(final JsonObjectBuilder json)
    throws IOException {
    final HttpPost create =
        new HttpPost(
            String.format("%s/%s", this.baseUri.toString(), "create")
        );
    try {
        create.setEntity(
            new StringEntity(
                json.build().toString(), ContentType.APPLICATION_JSON
            )
        );
        final JsonObject createResult = this.client.execute(
            create,
            new ReadJsonObject(
                new MatchStatus(
                    create.getURI(),
                    HttpStatus.SC_CREATED
                )
            )
        );
        if (!createResult.isEmpty()) {
            return new RtVolume(createResult,
                this.client,
                URI.create(
                    String.format("%s/%s", this.baseUri.toString(),
                        createResult.getString("Name"))
                ),
                this.docker
            );
        } else {
            throw new IOException(
                "Got empty response from Volumes.create() method"
            );
        }
    } finally {
        create.releaseConnection();
    }
}
 
Example 32
Source Project: blynk-server   Source File: HttpAPIPinsTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testPostEmailWithBody() throws Exception {
    HttpPost request = new HttpPost(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/email");
    String message = JsonParser.MAPPER.writeValueAsString(new EmailPojo("[email protected]", "Title", "Subject"));
    request.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }
}
 
Example 33
Source Project: devops-cm-client   Source File: TransportRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public HttpPost createTransport()
{
  HttpPost post = new HttpPost(createTransportUri(null, null));
  post.addHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
  return post;

}
 
Example 34
Source Project: AsuraFramework   Source File: GenericSmsSender.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * post 参数
 *
 * @param smsMessage
 */
@Override
protected HttpPost buildPostParam(SmsMessage smsMessage) throws UnsupportedEncodingException, URISyntaxException {
    URI uri = super.buildURIByConfig();
    HttpPost httpPost = new HttpPost(uri);
    GenericSmsSenderConfig config = (GenericSmsSenderConfig) this.getConfig();
    List<NameValuePair> formparams = new ArrayList<>();
    formparams.add(new BasicNameValuePair("accountName", config.getAccountName()));
    formparams.add(new BasicNameValuePair("password", config.getPassword()));
    formparams.add(new BasicNameValuePair("toPhone", smsMessage.getToPhone()));
    formparams.add(new BasicNameValuePair("content", smsMessage.getContent()));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, config.getCharset());
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 35
Source Project: cellery-distribution   Source File: RequestProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute http post request
 *
 * @param url         url
 * @param contentType content type
 * @param acceptType  accept type
 * @param authHeader  authorization header
 * @param payload     post payload
 * @return Closable http response
 * @throws APIException Api exception when an error occurred
 */
public String doPost(String url, String contentType, String acceptType, String authHeader, String payload)
        throws APIException {
    String returnObj = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Post payload: " + payload);
            log.debug("Post auth header: " + authHeader);
        }
        StringEntity payloadEntity = new StringEntity(payload);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(Constants.Utils.HTTP_CONTENT_TYPE, contentType);
        httpPost.setHeader(Constants.Utils.HTTP_RESPONSE_TYPE_ACCEPT, acceptType);
        httpPost.setHeader(Constants.Utils.HTTP_REQ_HEADER_AUTHZ, authHeader);
        httpPost.setEntity(payloadEntity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseStr = EntityUtils.toString(entity);
        int statusCode = response.getStatusLine().getStatusCode();

        if (log.isDebugEnabled()) {
            log.debug("Response status code: " + statusCode);
            log.debug("Response string : " + responseStr);
        }
        if (responseValidate(statusCode, responseStr)) {
            returnObj = responseStr;
        }
        closeClientConnection();
    } catch (IOException e) {
        String errorMessage = "Error occurred while executing the http Post connection.";
        log.error(errorMessage, e);
        throw new APIException(errorMessage, e);
    }
    return returnObj;
}
 
Example 36
Source Project: volley   Source File: HttpClientStackTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void createDeprecatedPostRequest() throws Exception {
    TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost();
    assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example 37
Source Project: product-emm   Source File: HttpClientStackTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void createPostRequestWithBody() throws Exception {
    TestRequest.PostWithBody request = new TestRequest.PostWithBody();
    assertEquals(request.getMethod(), Method.POST);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPost);
}
 
Example 38
Source Project: para   Source File: LinkedInAuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles an authentication request.
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	final String requestURI = request.getRequestURI();
	UserAuthentication userAuth = null;

	if (requestURI.endsWith(LINKEDIN_ACTION)) {
		String authCode = request.getParameter("code");
		if (!StringUtils.isBlank(authCode)) {
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String redirectURI = SecurityUtils.getRedirectUrl(request);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.LINKEDIN_PREFIX);
			String entity = Utils.formatMessage(PAYLOAD, authCode, Utils.urlEncode(redirectURI), keys[0], keys[1]);

			HttpPost tokenPost = new HttpPost(TOKEN_URL);
			tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
			tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
			try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
				if (resp1 != null && resp1.getEntity() != null) {
					Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
					if (token != null && token.containsKey("access_token")) {
						userAuth = getOrCreateUser(app, (String) token.get("access_token"));
					}
					EntityUtils.consumeQuietly(resp1.getEntity());
				}
			}
		}
	}

	return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
}
 
Example 39
Source Project: galaxy-sdk-java   Source File: MetricsHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set signature related headers when credential is properly set
 */
private MetricsHttpClient setAuthenticationHeaders(HttpPost post, byte[] data) {
  if (this.client != null && credential != null) {
    if (credential.getSecretKeyId() != null) {
      String host = this.host.toHostString();
      host = host.split(":")[0];
      post.setHeader(AuthenticationConstants.HK_HOST, host);

      // timestamp
      String timestamp = Long.toString(clock.getCurrentEpoch());
      post.setHeader(AuthenticationConstants.HK_TIMESTAMP, timestamp);
      post.setHeader(HttpKeys.MI_DATE, HttpUtils.getGMTDatetime(new Date()));

      // content md5
      String md5 = BytesUtil
          .bytesToHex(DigestUtil.digest(DigestUtil.DigestAlgorithm.MD5, data));
      post.setHeader(com.xiaomi.infra.galaxy.sds.thrift.AuthenticationConstants.HK_CONTENT_MD5, md5);
      LinkedListMultimap<String, String> headers = LinkedListMultimap.create();
      for (Header header : post.getAllHeaders()) {
        headers.put(header.getName().toLowerCase(), header.getValue());
      }
      try {
        String authString = "Galaxy-V3 "
            + credential.getSecretKeyId()
            + ":"
            + Signer.signToBase64(HttpMethod.POST, post.getURI(), headers,
              credential.getSecretKey(), SignAlgorithm.HmacSHA1);
        post.setHeader(AuthenticationConstants.HK_AUTHORIZATION, authString);
      } catch (Exception e) {
        throw new RuntimeException("Failed to sign", e);
      }
    } else {
      throw new RuntimeException("SecretKeyId must not be null");
    }
  }
  return this;
}
 
Example 40
Source Project: cxf   Source File: JAXRSMultipartTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipartRequestNoBody() throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + PORT + "/bookstore/books/image");
    String ct = "multipart/mixed";
    post.setHeader("Content-Type", ct);

    try {
        CloseableHttpResponse response = client.execute(post);
        assertEquals(400, response.getStatusLine().getStatusCode());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}