本文整理汇总了Java中org.apache.http.client.methods.HttpPost.setHeader方法的典型用法代码示例。如果您正苦于以下问题:Java HttpPost.setHeader方法的具体用法?Java HttpPost.setHeader怎么用?Java HttpPost.setHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.client.methods.HttpPost
的用法示例。
在下文中一共展示了HttpPost.setHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: callRC
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
* Call Limesurvey Remote Control.
*
* @param body the body of the request. Contains which method to call and the parameters
* @return the json element containing the result from the call
* @throws LimesurveyRCException the limesurvey rc exception
*/
public JsonElement callRC(LsApiBody body) throws LimesurveyRCException {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
String jsonBody = gson.toJson(body);
LOGGER.debug("API CALL JSON => " + jsonBody);
post.setEntity(new StringEntity(jsonBody));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String jsonResult = EntityUtils.toString(response.getEntity());
LOGGER.debug("API RESPONSE JSON => " + jsonResult);
JsonElement result = new JsonParser().parse(jsonResult).getAsJsonObject().get("result");
if (result.isJsonObject() && result.getAsJsonObject().has("status")) {
throw new LimesurveyRCException("Error from API : " + result.getAsJsonObject().get("status").getAsString());
}
return result;
} else {
throw new LimesurveyRCException("Expecting status code 200, got " + response.getStatusLine().getStatusCode() + " instead");
}
} catch (IOException e) {
throw new LimesurveyRCException("Exception while calling API : " + e.getMessage(), e);
}
}
示例2: query
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private <REQ, RESP> RESP query(REQ request, Class<RESP> clazz) throws IOException, DruidException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(configuration.getUrl());
StringEntity entity = new StringEntity(mapper.writeValueAsString(request), configuration.getCharset());
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
String content = EntityUtils.toString(response.getEntity(), configuration.getCharset());
try {
return mapper.readValue(content, clazz);
} catch (Exception ex) {
throw new DruidException(content);
} finally {
client.close();
}
}
示例3: executePost
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public String executePost(List<NameValuePair> urlParameters) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(this.url);
post.setHeader("User-Agent", USER_AGENT);
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
return result.toString();
}
示例4: testValidationFilterFailedNull
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
* Check the JAX-RS validation reject the null object in POST
*/
@Test
public void testValidationFilterFailedNull() throws IOException {
final HttpPost httppost = new HttpPost(BASE_URI + RESOURCE);
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader(ACCEPT_LANGUAGE, "EN");
final HttpResponse response = httpclient.execute(httppost);
Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
Assert.assertNotNull(content);
@SuppressWarnings("all")
final Map<String, Map<String, List<Map<String, Object>>>> result = (Map<String, Map<String, List<Map<String, Object>>>>) new ObjectMapperTrim()
.readValue(content, HashMap.class);
Assert.assertFalse(result.isEmpty());
final Map<String, List<Map<String, Object>>> errors = result.get("errors");
Assert.assertNotNull(errors);
Assert.assertEquals(1, errors.size());
log.info("### ENTRY ####" + errors.keySet().iterator().next());
Assert.assertNotNull(errors.get("wine"));
Assert.assertEquals(1, ((List<?>) errors.get("wine")).size());
Assert.assertEquals(1, ((Map<?, ?>) ((List<?>) errors.get("wine")).get(0)).size());
Assert.assertEquals(((Map<?, ?>) ((List<?>) errors.get("wine")).get(0)).get(RULE), "NotNull");
}
示例5: addAuthorizationToRequest
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
* Sends request to NGB server, retrieves an authorization token and adds it to an input request.
* This is required for secure requests.
* @param request to authorize
*/
protected void addAuthorizationToRequest(HttpRequestBase request) {
try {
HttpPost post = new HttpPost(serverParameters.getServerUrl() + serverParameters.getAuthenticationUrl());
StringEntity input = new StringEntity(serverParameters.getAuthPayload());
input.setContentType(APPLICATION_JSON);
post.setEntity(input);
post.setHeader(CACHE_CONTROL, CACHE_CONTROL_NO_CACHE);
post.setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded");
String result = RequestManager.executeRequest(post);
Authentication authentication = getMapper().readValue(result, Authentication.class);
request.setHeader("authorization", "Bearer " + authentication.getAccessToken());
} catch (IOException e) {
throw new ApplicationException("Failed to authenticate request", e);
}
}
示例6: send
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String base) throws Exception {
List<NameValuePair> formParams = new ArrayList<>();
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);
}
示例7: introspect
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
public String introspect(String token) throws IOException
{
HttpPost post = new HttpPost(_introspectionUri);
post.setHeader(ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
List<NameValuePair> params = new ArrayList<>(3);
params.add(new BasicNameValuePair("token", token));
params.add(new BasicNameValuePair("client_id", _clientId));
params.add(new BasicNameValuePair("client_secret", _clientSecret));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = _httpClient.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
_logger.severe(() -> "Got error from introspection server: " + response.getStatusLine().getStatusCode());
throw new IOException("Got error from introspection server: " + response.getStatusLine().getStatusCode());
}
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
示例8: post
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public String post(String url, String data) throws Exception {
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(data));
return execute(request);
}
示例9: send
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public boolean send() throws Exception
{
String url = host + postPath;
String postBody = rootJson.toString();
String sign = DigestUtils.md5Hex("POST" + url + postBody + appMasterSecret);
url = url + "?sign=" + sign;
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
StringEntity se = new StringEntity(postBody, "UTF-8");
post.setEntity(se);
// Send the post request and get the response
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
}
if (status == 200)
{
LOGGER.info("Notification sent successfully.");
return true;
}
else
{
LOGGER.error("Failed to send the notification! Result:{}", result);
return false;
}
}
示例10: send
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public static boolean send(DingMsgSender sender, String content, String token) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pools).build();
HttpPost post = new HttpPost(DingConfig.url + token);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(buildJsonMessage(sender, content), "UTF-8"));
try(CloseableHttpResponse httpResponse = httpClient.execute(post)) {
return convertResponse(httpResponse.getEntity());
} catch (IOException e) {
logger.error("send error", e);
return false;
}
}
示例11: servicePost
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private HttpResponse servicePost(JsonWrapper qpp) throws IOException {
HttpEntity entity = new ByteArrayEntity(qpp.toString().getBytes("UTF-8"));
HttpPost request = new HttpPost(SERVICE_URL);
request.setHeader("Content-Type", "application/json");
request.setEntity(entity);
return client.execute(request);
}
示例12: createHttpWithPost
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
* 创建网络请求 post请求
* @param url
* @return
*/
public CloseableHttpResponse createHttpWithPost(String url) {
// 获取客户端连接对象
CloseableHttpClient httpClient = getHttpClient();
// 创建Post请求对象
HttpPost httpPost = new HttpPost(url);
if (Preconditions.isNotBlank(httpParam)) {
boolean autoReferer = httpParam.isAutoReferer();
Map<String,String> header = httpParam.getHeader();
if (Preconditions.isNotBlank(header)) {
if (autoReferer && !header.containsKey("Referer")) {
header.put("Referer", Utils.getReferer(url));
}
for (String key : header.keySet()) {
httpPost.setHeader(key,header.get(key));
}
}
}
CloseableHttpResponse response = null;
// 执行请求
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
示例13: uploadContents
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public String uploadContents(String contents) throws Exception {
if (!rootJson.has("appkey") || !rootJson.has("timestamp")) {
throw new Exception("appkey, timestamp needs to be set.");
}
// Construct the json string
JSONObject uploadJson = new JSONObject();
uploadJson.put("appkey", rootJson.getString("appkey"));
uploadJson.put("timestamp", rootJson.getString("timestamp"));
uploadJson.put("content", contents);
// Construct the request
String url = host + uploadPath;
String postBody = uploadJson.toString();
String sign = DigestUtils.md5Hex("POST" + url + postBody + appMasterSecret);
url = url + "?sign=" + sign;
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
StringEntity se = new StringEntity(postBody, "UTF-8");
post.setEntity(se);
// Send the post request and get the response
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
// Decode response string and get file_id from it
JSONObject respJson = new JSONObject(result.toString());
String ret = respJson.getString("ret");
if (!ret.equals("SUCCESS")) {
throw new Exception("Failed to upload file");
}
JSONObject data = respJson.getJSONObject("data");
String fileId = data.getString("file_id");
// Set file_id into rootJson using setPredefinedKeyValue
setPredefinedKeyValue("file_id", fileId);
return fileId;
}
示例14: sendZipfile
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
Sends a single zip file
@param zipFile Name of the zip file in the data directory.
@throws IOException
*/
private void sendZipfile(String zipFile) throws IOException
{
logger.debug("Sending {}", zipFile);
HttpPost post = new HttpPost(m_remoteUrl+"/api/v1/datapoints");
File zipFileObj = new File(m_dataDirectory, zipFile);
FileInputStream zipStream = new FileInputStream(zipFileObj);
post.setHeader("Content-Type", "application/gzip");
post.setEntity(new InputStreamEntity(zipStream, zipFileObj.length()));
try(CloseableHttpResponse response = m_client.execute(post))
{
zipStream.close();
if (response.getStatusLine().getStatusCode() == 204)
{
zipFileObj.delete();
}
else
{
ByteArrayOutputStream body = new ByteArrayOutputStream();
response.getEntity().writeTo(body);
logger.error("Unable to send file " + zipFile + ": " + response.getStatusLine() +
" - "+ body.toString("UTF-8"));
}
}
}
示例15: doInBackground
import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://djtrinity.in/app/api/events.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}