本文整理汇总了Java中org.apache.http.entity.StringEntity.setContentType方法的典型用法代码示例。如果您正苦于以下问题:Java StringEntity.setContentType方法的具体用法?Java StringEntity.setContentType怎么用?Java StringEntity.setContentType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.entity.StringEntity
的用法示例。
在下文中一共展示了StringEntity.setContentType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: notifyHunter
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
public String notifyHunter(byte[] content) throws IOException {
try {
String request = new String(content);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
StringEntity entity = new StringEntity(json);
entity.setContentType("applicaiton/json");
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error Notifying Probe Server!";
}
示例2: sendHttpPost
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Override
public <REQ> CloseableHttpResponse sendHttpPost(String url, REQ request) {
CloseableHttpResponse execute = null;
String requestJson = GsonUtils.toJson(request);
try {
LOGGER.log(Level.FINER, "Send POST request:" + requestJson + " to url-" + url);
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(requestJson, "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
execute = this.httpClientFactory.getHttpClient().execute(httpPost);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "was unable to send POST request:" + requestJson
+ " (displaying first 1000 chars) from url-" + url, e);
}
return execute;
}
示例3: testService
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@RequestMapping(value = "testService", method = RequestMethod.POST)
public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort,
@RequestBody GrpcServiceTestModel model) throws Exception {
String serviceUrl = "http://" + ipPort + "/service/test";
HttpPost request = new HttpPost(serviceUrl);
request.addHeader("content-type", "application/json");
request.addHeader("Accept", "application/json");
try {
StringEntity entity = new StringEntity(gson.toJson(model), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
request.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String minitorJson = EntityUtils.toString(httpResponse.getEntity());
Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType());
return response;
}
} catch (Exception e) {
throw e;
}
return null;
}
示例4: executeHttpPost
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
/**
* Performs HTTP Post request with OAuth authentication for the endpoint
* with the given path, with the given JSON as payload and the given HTTP
* headers.
*
* @param path
* the path to be called.
* @param headers
* map with HTTP header names and values to be included in the
* request.
* @param jsonContent
* the JSON content to be posted.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
CloseableHttpResponse executeHttpPost(String path, Map<String, String> headers, String jsonContent)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
HttpPost httpPost = createHttpPost(baseUri + path);
if (headers != null) {
for (String header : headers.keySet()) {
httpPost.addHeader(header, headers.get(header));
}
}
if (jsonContent != null) {
StringEntity input = new StringEntity(jsonContent);
input.setContentType(MediaType.APPLICATION_JSON);
httpPost.setEntity(input);
}
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
return response;
}
示例5: executeHttpPost
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
/**
* Performs HTTP Post request for the end point with the given path, with
* the given JSON as payload.
*
* @param path
* the path to be called.
* @param jsonContent
* the JSON content to be posted.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
public CloseableHttpResponse executeHttpPost(String path, String jsonContent)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
HttpPost httpPost = createHttpPost(baseUri + path);
StringEntity input = new StringEntity(jsonContent, StandardCharsets.UTF_8);
input.setContentType(APPLICATION_JSON);
httpPost.setEntity(input);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
return response;
}
开发者ID:SAP,项目名称:cloud-ariba-discovery-rfx-to-external-marketplace-ext,代码行数:29,代码来源:OpenApisEndpoint.java
示例6: createPutRequest
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
/**
*
* @param payload
* @return
*/
protected HttpPut createPutRequest(final Object value, final String collection) {
try {
logger.debug("received value {}, and collection {}", value, collection);
final Map<?, ?> valueMap = new LinkedHashMap<>((Map<?,?>)value);
final Object url = valueMap.remove(URL);
final URIBuilder uriBuilder = getURIBuilder(null == url ? UUID.randomUUID().toString() : url.toString(), collection);
final String jsonString = MAPPER.writeValueAsString(valueMap);
final HttpPut request = new HttpPut(uriBuilder.build());
final StringEntity params = new StringEntity(jsonString, "UTF-8");
params.setContentType(DEFAULT_CONTENT_TYPE.toString());
request.setEntity(params);
return request;
} catch (URISyntaxException | JsonProcessingException | MalformedURLException e) {
logger.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
示例7: post
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
public static HttpPost post(String url, String body) {
StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
entity.setContentType(ContentType.APPLICATION_JSON.toString());
HttpPost req = new HttpPost(url);
req.setEntity(entity);
return req;
}
示例8: postReport
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
/**
* Sends the {@code report} to the {@code controller}.
* @param controller the controller to contact.
* @param client the HTTP client to contact with.
* @param report the report to send.
* @throws IOException when report cannot be sent.
*/
public static void postReport(Controller controller, Report report, CloseableHttpClient client) throws IOException {
String reportResource = controller.getLogResource();
String json = report.toJson();
HttpHost proxy = controller.getProxy(AppConfigurationService.getConfigurations().getProxy()).toHttpHost();
HttpPost httpPost = new HttpPost(reportResource);
StringEntity data = new StringEntity(json);
data.setContentType("application/json");
httpPost.setEntity(data);
controller.getAuthentication(AppConfigurationService.getConfigurations().getAuthentication())
.forEach(httpPost::setHeader);
if (proxy != null) httpPost.setConfig(RequestConfig.custom().setProxy(proxy).build());
try (CloseableHttpResponse response = client.execute(httpPost)) {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
}
示例9: testSimpleUTF16
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Test
public void testSimpleUTF16() throws IOException, InterruptedException {
StringEntity input = new StringEntity("[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
+ "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]", "UTF-16");
input.setContentType("application/json; charset=utf-16");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Assert.assertEquals(HttpServletResponse.SC_OK,
response.getStatusLine().getStatusCode());
Transaction tx = channel.getTransaction();
tx.begin();
Event e = channel.take();
Assert.assertNotNull(e);
Assert.assertEquals("b", e.getHeaders().get("a"));
Assert.assertEquals("random_body", new String(e.getBody(), "UTF-16"));
e = channel.take();
Assert.assertNotNull(e);
Assert.assertEquals("f", e.getHeaders().get("e"));
Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-16"));
tx.commit();
tx.close();
}
示例10: addAuthorizationToRequest
import org.apache.http.entity.StringEntity; //导入方法依赖的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);
}
}
示例11: testSingleEvent
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Test
public void testSingleEvent() throws Exception {
StringEntity input = new StringEntity("[{\"headers\" : {\"a\": \"b\"},\"body\":"
+ " \"random_body\"}]");
input.setContentType("application/json");
postRequest.setEntity(input);
httpClient.execute(postRequest);
Transaction tx = channel.getTransaction();
tx.begin();
Event e = channel.take();
Assert.assertNotNull(e);
Assert.assertEquals("b", e.getHeaders().get("a"));
Assert.assertEquals("random_body", new String(e.getBody(),"UTF-8"));
tx.commit();
tx.close();
}
示例12: setPutEntity
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Override
public void setPutEntity(String xmlstr, HttpPut httpput) throws UnsupportedEncodingException {
StringEntity input = new StringEntity(xmlstr);
if (xmlstr != null && !xmlstr.isEmpty()) {
input.setContentType("application/xml");
}
httpput.setEntity(input);
}
示例13: postJson
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
/** post
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @param obj post obj 提交json
* @return
* @throws IOException
*/
public <T> String postJson(String url, Map<String, String> queries, T obj) throws IOException {
String responseBody = "";
CloseableHttpClient httpClient = getHttpClient();
StringBuilder sb = new StringBuilder(url);
appendQueryParams(queries, sb);
//指定url,和http方式
HttpPost httpPost = new HttpPost(sb.toString());
if (SetTimeOut) {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SocketTimeout)
.setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig);
}
//添加参数
String jsonbody = null;
if (obj != null) {
jsonbody = JSONObject.toJSONString(obj);
}
//设置参数到请求对象中
StringEntity stringEntity = new StringEntity(jsonbody,"utf-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
//请求数据
CloseableHttpResponse response = httpClient.execute(httpPost);
responseBody = getResponseString(responseBody, response);
return responseBody;
}
示例14: registerTwoRoutesTest
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Test
public void registerTwoRoutesTest(TestContext context) throws IOException {
TestRest testRest = new TestRest();
TestPostRest testPostRest = new TestPostRest();
Router router = RestRouter.register(vertx, testRest, testPostRest);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(PORT);
final Async async = context.async();
// check if both are active
Dummy json = new Dummy("test", "me");
StringEntity input = new StringEntity(JsonUtils.toJson(json));
input.setContentType("application/json");
/* HttpPost request = (HttpPost) HttpUtils.post(ROOT_PATH + "/test/json/post", null, null, input, null);
HttpResponse response = HttpUtils.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
String output = HttpUtils.getContentAsString(response);
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", output);
*/
// 2nd REST
HttpPost request = (HttpPost) HttpUtils.post(ROOT_PATH + "/post/json", null, null, input, null);
HttpResponse response = HttpUtils.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
String output = HttpUtils.getContentAsString(response);
assertEquals("{\"name\":\"Received-test\",\"value\":\"Received-me\"}", output);
async.complete();
}
示例15: testSimple
import org.apache.http.entity.StringEntity; //导入方法依赖的package包/类
@Test
public void testSimple() throws IOException, InterruptedException {
StringEntity input = new StringEntity("[{\"headers\":{\"a\": \"b\"},\"body\": \"random_body\"},"
+ "{\"headers\":{\"e\": \"f\"},\"body\": \"random_body2\"}]");
//if we do not set the content type to JSON, the client will use
//ISO-8859-1 as the charset. JSON standard does not support this.
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Assert.assertEquals(HttpServletResponse.SC_OK,
response.getStatusLine().getStatusCode());
Transaction tx = channel.getTransaction();
tx.begin();
Event e = channel.take();
Assert.assertNotNull(e);
Assert.assertEquals("b", e.getHeaders().get("a"));
Assert.assertEquals("random_body", new String(e.getBody(), "UTF-8"));
e = channel.take();
Assert.assertNotNull(e);
Assert.assertEquals("f", e.getHeaders().get("e"));
Assert.assertEquals("random_body2", new String(e.getBody(), "UTF-8"));
tx.commit();
tx.close();
}