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

The following examples show how to use org.apache.http.client.methods.HttpPost#setConfig() . 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: HttpUtil.java    From Dolphin with Apache License 2.0 6 votes vote down vote up
private static HttpPost createPost(String url, Map<String, String> params) {
    HttpPost post = new HttpPost(url);
    post.setConfig(CONFIG);
    if (params != null) {
        List<NameValuePair> nameValuePairList = Lists.newArrayList();
        Set<String> keySet = params.keySet();

        for (String key : keySet) {
            nameValuePairList.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
        } catch (UnsupportedEncodingException ignored) {
        }
    }

    return post;
}
 
Example 2
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a HttpPost for the given configuration.
 * <p>The default implementation creates a standard HttpPost with
 * "application/x-java-serialized-object" as "Content-Type" header.
 * @param config the HTTP invoker configuration that specifies the
 * target service
 * @return the HttpPost instance
 * @throws java.io.IOException if thrown by I/O methods
 */
protected HttpPost createHttpPost(HttpInvokerClientConfiguration config) throws IOException {
	HttpPost httpPost = new HttpPost(config.getServiceUrl());

	RequestConfig requestConfig = createRequestConfig(config);
	if (requestConfig != null) {
		httpPost.setConfig(requestConfig);
	}

	LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
	if (localeContext != null) {
		Locale locale = localeContext.getLocale();
		if (locale != null) {
			httpPost.addHeader(HTTP_HEADER_ACCEPT_LANGUAGE, locale.toLanguageTag());
		}
	}

	if (isAcceptGzipEncoding()) {
		httpPost.addHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
	}

	return httpPost;
}
 
Example 3
Source File: HttpClientManage.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 提交json数据
 *
 * @param url
 * @param json
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
    // 创建http POST请求
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(this.requestConfig);

    if (json != null) {
        // 构造一个请求实体
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(stringEntity);
    }
    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = this.httpClient.execute(httpPost);
        return new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity(), "UTF-8"));
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example 4
Source File: MaterialNewsInfoRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
public WxMpMaterialNews 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);
  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);
  }
}
 
Example 5
Source File: SimplePostRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws WxErrorException, ClientProtocolException, IOException {
  HttpPost httpPost = new HttpPost(uri);
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  if (postEntity != null) {
    StringEntity entity = new StringEntity(postEntity, Consts.UTF_8);
    httpPost.setEntity(entity);
  }

  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);
    }
    return responseContent;
  }
}
 
Example 6
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 7
Source File: MaterialDeleteRequestExecutor.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
public Boolean 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);
  String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
  WxError error = WxError.fromJson(responseContent);
  if (error.getErrorCode() != 0) {
    throw new WxErrorException(error);
  } else {
    return true;
  }
}
 
Example 8
Source File: HttpUtilManager.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
public String requestHttpPost(String url_prex, String url, Map<String, String> params)
		throws HttpException, IOException {
	IdleConnectionMonitor();
	url = url_prex + url;
	HttpPost method = this.httpPostMethod(url);
	List<NameValuePair> valuePairs = this.convertMap2PostParams(params);
	UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
	method.setEntity(urlEncodedFormEntity);
	method.setConfig(requestConfig);
	HttpResponse response = client.execute(method);
	// System.out.println(method.getURI());
	HttpEntity entity = response.getEntity();

	if (entity == null) {
		return "";
	}
	InputStream is = null;
	String responseData = "";
	try {
		is = entity.getContent();
		responseData = IOUtils.toString(is, "UTF-8");
	} finally {
		if (is != null) {
			is.close();
		}
	}
	return responseData;

}
 
Example 9
Source File: CommonService.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private HttpPost postMethod(String uri, HttpServletRequest request) {
    StringEntity entity;
    if (request.getContentType().contains(FORMAT_TYPE)) {
        entity = this.jsonData(request);
    } else {
        entity = this.formData(request);
    }
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setHeader(CONTENT_TYPE, request.getHeader(CONTENT_TYPE));
    httpPost.setEntity(entity);
    httpPost.setConfig(getRequestConfig());
    return httpPost;
}
 
Example 10
Source File: HttpClientUtil.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * @param url
 * @param data
 * @return
 */
private static HttpPost postForm(String url, JSONObject data, HttpHost httpHost) {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig(httpHost));
    httpPost.setHeader(CONNECTION, KEEP_ALIVE);
    httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
    httpPost.setHeader(ACCEPT, APPLICATION_JSON);
    StringEntity entity = new StringEntity(data.toString(), UTF8);
    httpPost.setEntity(entity);
    return httpPost;
}
 
Example 11
Source File: HomeGraphAPI.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private HttpPost createPost(String url, ContentType contentType, HttpEntity body) {
   HttpPost post = new HttpPost(url);
   post.setConfig(requestConfig);
   post.setHeader(HttpHeaders.CONTENT_TYPE, contentType.getMimeType());
   post.setEntity(body);
   return post;
}
 
Example 12
Source File: SparkJobServerClientImpl.java    From SparkJobServerClient with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean uploadSparkJobJar(InputStream jarData, String appName)
    throws SparkJobServerClientException {
	if (jarData == null || appName == null || appName.trim().length() == 0) {
		throw new SparkJobServerClientException("Invalid parameters.");
	}
	HttpPost postMethod = new HttpPost(jobServerUrl + "jars/" + appName);
       postMethod.setConfig(getRequestConfig());
	setAuthorization(postMethod);
	final CloseableHttpClient httpClient = buildClient();
	try {
		ByteArrayEntity entity = new ByteArrayEntity(IOUtils.toByteArray(jarData));
		postMethod.setEntity(entity);
		entity.setContentType("application/java-archive");
		HttpResponse response = httpClient.execute(postMethod);
		int statusCode = response.getStatusLine().getStatusCode();
		getResponseContent(response.getEntity());
		if (statusCode == HttpStatus.SC_OK) {
			return true;
		}
	} catch (Exception e) {
		logger.error("Error occurs when uploading spark job jars:", e);
	} finally {
		close(httpClient);
		closeStream(jarData);
	}
	return false;
}
 
Example 13
Source File: WorkSpaceAdapter.java    From emissary with Apache License 2.0 5 votes vote down vote up
/**
 * Outbound open tells a remote WorkSpace to start pulling data
 * 
 * @param place the remote place to contact
 * @param space the location of the work distributor
 */
public EmissaryResponse outboundOpenWorkSpace(final String place, final String space) {

    final String placeUrl = KeyManipulator.getServiceHostURL(place);
    final HttpPost method = new HttpPost(placeUrl + CONTEXT + "/WorkSpaceClientOpenWorkSpace.action");

    final List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(CLIENT_NAME, place));
    nvps.add(new BasicNameValuePair(SPACE_NAME, space));
    method.setEntity(new UrlEncodedFormEntity(nvps, java.nio.charset.Charset.defaultCharset()));
    // set a timeout in case a node is unresponsive
    method.setConfig(RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build());

    return send(method);
}
 
Example 14
Source File: WxMpTemplateMsgSender.java    From WePush with MIT License 4 votes vote down vote up
@Override
public SendResult asyncSend(String[] msgData) {
    SendResult sendResult = new SendResult();
    BoostForm boostForm = BoostForm.getInstance();

    try {
        if (PushControl.dryRun) {
            // 已成功+1
            PushData.increaseSuccess();
            boostForm.getSuccessCountLabel().setText(String.valueOf(PushData.successRecords));
            // 保存发送成功
            PushData.sendSuccessList.add(msgData);
            // 总进度条
            boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            String openId = msgData[0];
            WxMpTemplateMessage wxMessageTemplate = wxMpTemplateMsgMaker.makeMsg(msgData);
            wxMessageTemplate.setToUser(openId);

            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + wxMpService.getAccessToken();
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(wxMessageTemplate.toJson(), Consts.UTF_8);
            httpPost.setEntity(entity);
            if (wxMpService.getRequestHttp().getRequestHttpProxy() != null) {
                RequestConfig config = RequestConfig.custom().setProxy((HttpHost) wxMpService.getRequestHttp().getRequestHttpProxy()).build();
                httpPost.setConfig(config);
            }
            Future<HttpResponse> httpResponseFuture = getCloseableHttpAsyncClient().execute(httpPost, new CallBack(msgData));
            BoostPushRunThread.futureList.add(httpResponseFuture);
        }
    } catch (Exception e) {
        // 总发送失败+1
        PushData.increaseFail();
        boostForm.getFailCountLabel().setText(String.valueOf(PushData.failRecords));

        // 保存发送失败
        PushData.sendFailList.add(msgData);

        // 失败异常信息输出控制台
        ConsoleUtil.boostConsoleOnly("发送失败:" + e.toString() + ";msgData:" + JSONUtil.toJsonPrettyStr(msgData));
        // 总进度条
        boostForm.getCompletedProgressBar().setValue(PushData.successRecords.intValue() + PushData.failRecords.intValue());

        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(e.toString());
        return sendResult;
    }

    return sendResult;
}
 
Example 15
Source File: DefaultAbsSender.java    From TelegramBots with MIT License 4 votes vote down vote up
private HttpPost configuredHttpPost(String url) {
    HttpPost httppost = new HttpPost(url);
    httppost.setConfig(requestConfig);
    return httppost;
}
 
Example 16
Source File: WxMpServiceImpl.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) {
  String nonce_str = System.currentTimeMillis() + "";

  SortedMap<String, String> packageParams = new TreeMap<String, String>();
  packageParams.put("appid", wxMpConfigStorage.getAppId());
  packageParams.put("mch_id", wxMpConfigStorage.getPartnerId());
  if (transactionId != null && !"".equals(transactionId.trim()))
    packageParams.put("transaction_id", transactionId);
  else if (outTradeNo != null && !"".equals(outTradeNo.trim()))
    packageParams.put("out_trade_no", outTradeNo);
  else
    throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given.");
  packageParams.put("nonce_str", nonce_str);
  packageParams.put("sign", WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey()));

  StringBuilder request = new StringBuilder("<xml>");
  for (Entry<String, String> para : packageParams.entrySet()) {
    request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey()));
  }
  request.append("</xml>");

  HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
  if (httpProxy != null) {
    RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
    httpPost.setConfig(config);
  }

  StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
  httpPost.setEntity(entity);
  try {
    CloseableHttpResponse response = httpClient.execute(httpPost);
    String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
    XStream xstream = XStreamInitializer.getInstance();
    xstream.alias("xml", WxMpPayResult.class);
    WxMpPayResult wxMpPayResult = (WxMpPayResult) xstream.fromXML(responseContent);
    return wxMpPayResult;
  } catch (IOException e) {
    throw new RuntimeException("Failed to query order due to IO exception.", e);
  }
}
 
Example 17
Source File: TelegramBot.java    From telegram-notifications-plugin with MIT License 4 votes vote down vote up
private HttpPost configuredHttpPost(String url) {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    return httpPost;
}
 
Example 18
Source File: RestConnector.java    From pnc with Apache License 2.0 4 votes vote down vote up
private void configureRequest(String accessToken, HttpPost request) {
    request.setConfig(httpClientConfig().build());
    request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    request.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
}
 
Example 19
Source File: HttpUtils.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param protocol
 * @param url
 * @param paraMap
 * @return
 * @throws Exception
 */
public static String doPost(String protocol, String url,
                            Map<String, Object> paraMap) throws Exception {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse resp = null;
    String rtnValue = null;
    try {
        if (protocol.equals("http")) {
            httpClient = HttpClients.createDefault();
        } else {
            // 获取https安全客户端
            httpClient = HttpUtils.getHttpsClient();
        }

        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (null != paraMap && paraMap.size() > 0) {
            for (Entry<String, Object> entry : paraMap.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString()));
            }
        }

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SO_TIMEOUT)
                .setConnectTimeout(CONNECT_TIMEOUT).build();// 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        httpPost.setEntity(new UrlEncodedFormEntity(list, CHARSET_UTF_8));
        resp = httpClient.execute(httpPost);
        rtnValue = EntityUtils.toString(resp.getEntity(), CHARSET_UTF_8);

    } catch (Exception e) {
        throw e;
    } finally {
        if (null != resp) {
            resp.close();
        }
        if (null != httpClient) {
            httpClient.close();
        }
    }

    return rtnValue;
}
 
Example 20
Source File: SparkJobServerClientImpl.java    From SparkJobServerClient with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public SparkJobResult startJob(String data, Map<String, String> params) throws SparkJobServerClientException {
	final CloseableHttpClient httpClient = buildClient();
	try {
		if (params == null || params.isEmpty()) {
			throw new SparkJobServerClientException("The given params is null or empty.");
		}
		if (params.containsKey(ISparkJobServerClientConstants.PARAM_APP_NAME) &&
		    params.containsKey(ISparkJobServerClientConstants.PARAM_CLASS_PATH)) {
			StringBuffer postUrlBuff = new StringBuffer(jobServerUrl);
			postUrlBuff.append("jobs?");
			int num = params.size();
			for (String key : params.keySet()) {
				postUrlBuff.append(key).append('=').append(params.get(key));
				num--;
				if (num > 0) {
					postUrlBuff.append('&');
				}
			}
			HttpPost postMethod = new HttpPost(postUrlBuff.toString());
			postMethod.setConfig(getRequestConfig());
               setAuthorization(postMethod);
               if (data != null) {
				StringEntity strEntity = new StringEntity(data);
				strEntity.setContentEncoding("UTF-8");
				strEntity.setContentType("text/plain");
				postMethod.setEntity(strEntity);
			}
			
			HttpResponse response = httpClient.execute(postMethod);
			String resContent = getResponseContent(response.getEntity());
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
				return parseResult(resContent);
			} else {
				logError(statusCode, resContent, true);
			}
		} else {
			throw new SparkJobServerClientException("The given params should contains appName and classPath");
		}
	} catch (Exception e) {
		processException("Error occurs when trying to start a new job:", e);
	} finally {
		close(httpClient);
	}
	return null;
}