本文整理汇总了Java中org.apache.http.entity.StringEntity类的典型用法代码示例。如果您正苦于以下问题:Java StringEntity类的具体用法?Java StringEntity怎么用?Java StringEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
StringEntity类属于org.apache.http.entity包,在下文中一共展示了StringEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeRequest
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
/**
* Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}.
* The request type is determined by the {@code headers} param.
*
* @param request A {@link String} representation of a request object. Can be JSON object, form data, etc...
* @param serviceUrl The service URL to sent the request to
* @param headers An array of {@link Header} objects, used to determine the request type
* @return {@link String} response from the service (representing JSON object)
* @throws IOException if the connection is interrupted or the response is unparsable
*/
public String executeRequest(String request, String serviceUrl, Header[] headers) throws IOException {
HttpPost httpPost = new HttpPost(serviceUrl);
httpPost.setHeaders(headers);
httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8")));
if (logger.isDebugEnabled()) {
logger.debug("Sent " + request);
}
HttpResponse response = httpClient.execute(httpPost);
String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET);
if (logger.isDebugEnabled()) {
logger.debug("Received " + responseJSON);
}
return responseJSON;
}
示例2: uploadContents
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public String uploadContents(String contents) throws Exception {
if (!rootJson.has("appkey") || !rootJson.has("timestamp") || !rootJson.has("validation_token")) {
throw new Exception("appkey, timestamp and validation_token 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("validation_token", rootJson.getString("validation_token"));
uploadJson.put("content", contents);
// Construct the request
String url = host + uploadPath;
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
StringEntity se = new StringEntity(uploadJson.toString(), "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;
}
示例3: simplePost
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
/**
* Simple Http Post.
*
* @param path the path
* @param payload the payload
* @return the closeable http response
* @throws URISyntaxException the URI syntax exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws MininetException the MininetException
*/
public CloseableHttpResponse simplePost(String path, String payload)
throws URISyntaxException, IOException, MininetException {
URI uri = new URIBuilder()
.setScheme("http")
.setHost(mininetServerIP.toString())
.setPort(mininetServerPort.getPort())
.setPath(path)
.build();
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpPost request = new HttpPost(uri);
request.setConfig(config);
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(payload));
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 300) {
throw new MininetException(String.format("failure - received a %d for %s.",
response.getStatusLine().getStatusCode(), request.getURI().toString()));
}
return response;
}
示例4: sendHttpPut
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
@Override
public <REQ> CloseableHttpResponse sendHttpPut(String url, REQ request) {
CloseableHttpResponse execute = null;
String requestJson = GsonUtils.toJson(request);
try {
LOGGER.log(Level.FINER, "Send PUT request:" + requestJson + " to url-" + url);
HttpPut httpPut = new HttpPut(url);
StringEntity entity = new StringEntity(requestJson, "UTF-8");
entity.setContentType("application/json");
httpPut.setEntity(entity);
execute = this.httpClientFactory.getHttpClient().execute(httpPut);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Was unable to send PUT request:" + requestJson
+ " (displaying first 1000 chars) from url-" + url, e);
}
return execute;
}
示例5: postUrl
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public static String postUrl(String url, String body) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");
//请求超时 ,连接超时
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
//读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
try {
StringEntity entity = new StringEntity(body, "UTF-8");
httppost.setEntity(entity);
System.out.println(entity.toString());
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String charsetName = EntityUtils.getContentCharSet(response.getEntity());
//System.out.println(charsetName + "<<<<<<<<<<<<<<<<<");
String rs = EntityUtils.toString(response.getEntity());
//System.out.println( ">>>>>>" + rs);
return rs;
} else {
//System.out.println("Eorr occus");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return "";
}
示例6: handle
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
RequestLine line = request.getRequestLine();
Uri uri = Uri.parse(line.getUri());
DatabaseDataEntity entity;
if (uri != null) {
String database = uri.getQueryParameter("database");
String tableName = uri.getQueryParameter("table");
entity = getDataResponse(database, tableName);
if (entity != null) {
response.setStatusCode(200);
response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
return;
}
}
entity = new DatabaseDataEntity();
entity.setDataList(new ArrayList<Map<String, String>>());
entity.setCode(BaseEntity.FAILURE_CODE);
response.setStatusCode(200);
response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
示例7: login
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public static String login(String randCode) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.loginUrl);
httpPost.addHeader(CookieManager.cookieHeader());
String param = "username=" + encode(UserConfig.username) + "&password=" + encode(UserConfig.password) + "&appid=otn";
httpPost.setEntity(new StringEntity(param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
result = EntityUtils.toString(response.getEntity());
CookieManager.touch(response);
ResultManager.touch(result, new ResultKey("uamtk", "uamtk"));
} catch (IOException e) {
logger.error("login error", e);
}
return result;
}
示例8: checkOrderInfo
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public static String checkOrderInfo(TrainQuery query) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo);
httpPost.addHeader(CookieManager.cookieHeader());
httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("checkUser error", e);
}
return result;
}
示例9: setDefaultUser
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(host, 8002),
new UsernamePasswordCredentials("admin", "admin"));
String body = "{\"default-user\": \""+usr+"\"}";
HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default");
put.addHeader("Content-type", "application/json");
put.setEntity(new StringEntity(body));
HttpResponse response2 = client.execute(put);
HttpEntity respEntity = response2.getEntity();
if(respEntity != null){
String content = EntityUtils.toString(respEntity);
System.out.println(content);
}
}
示例10: 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;
}
示例11: doPost
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
示例12: postMessage
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public boolean postMessage(String url, String message) {
boolean ret = true;
try {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(URL + url);
StringEntity se = new StringEntity(message);
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
ret = false;
}
client.close();
} catch (Exception e) {
e.printStackTrace();
ret = false;
System.exit(-1);
}
return ret;
}
示例13: createIndex
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
/**
* Creates the specified index in ElasticSearch
*
* @param indexName
* the index name to augment
* @param typeName
* the type name to augment
* @param id
* the id of the document to add
* @param jsonDocument
* the String JSON document to add
*/
protected static void createIndex(String indexName) {
try {
// Create our expand / search indices
String endpoint = String.format("/%s", indexName);
Map<String, String> params = new HashMap<String, String>();
StringEntity requestBody = new StringEntity(INDEX_JSON);
Response resp = client.performRequest("PUT", endpoint, params, requestBody, contentTypeHeader);
staticLogger.debug("Response: " + resp.getStatusLine());
} catch (IOException e) {
// Ignore this...? probably already exists
staticLogger.error(e.getMessage(), e);
if (e instanceof UnsupportedEncodingException) {
staticLogger.error("Error encoding JSON: " + e.getMessage(), e);
return;
}
}
}
示例14: doPost
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
public static String doPost(String url, String json) throws Exception {
try {
CloseableHttpClient client = getHttpClient(url);
HttpPost post = new HttpPost(url);
config(post);
logger.info("====> Executing request: " + post.getRequestLine());
if (!StringUtils.isEmpty(json)) {
StringEntity s = new StringEntity(json, "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
}
String responseBody = client.execute(post, getStringResponseHandler());
logger.info("====> Getting response from request " + post.getRequestLine() + " The responseBody: " + responseBody);
return responseBody;
} catch (Exception e) {
if (e instanceof HttpHostConnectException || e.getCause() instanceof ConnectException) {
throw new ConnectException("====> 连接服务器" + url + "失败: " + e.getMessage());
}
logger.error("====> HttpRequestUtil.doPost: " + e.getMessage(), e);
}
return null;
}
示例15: getRequest
import org.apache.http.entity.StringEntity; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
String requestURL = "https://samurai.sipgate.net/RPC2";
HttpPost httpPost = new HttpPost(requestURL);
// TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
String userpassword = acc.username + ":" + acc.data;
String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
httpPost.addHeader("Content-Type", "text/xml");
// prepare POST body
String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";
// set POST body
HttpEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
return httpPost;
}