Here are the examples of the java api org.apache.http.client.methods.HttpPost.setEntity() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1752 Examples
19
Source : HttpClientConnection.java
with Apache License 2.0
from yunhaibin
with Apache License 2.0
from yunhaibin
public void sendRequest() throws IOException {
request.setEnreplacedy(new ByteArrayEnreplacedy(output.toByteArray()));
this.response = httpClient.execute(request);
}
19
Source : SchedulerRequest.java
with Apache License 2.0
from tlw-ray
with Apache License 2.0
from tlw-ray
public void submit(AbstractMeta meta) {
try {
httpPost.setEnreplacedy(buildSchedulerRequestEnreplacedy(meta));
httpclient.execute(httpPost);
logMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
19
Source : MyHttpClient.java
with Apache License 2.0
from SwiftyWang
with Apache License 2.0
from SwiftyWang
public String executePostRequest(String path, List<NameValuePair> params) {
httpClient = new DefaultHttpClient(httpParameters);
String ret = null;
try {
httpPost = new HttpPost(path);
httpEnreplacedy = new UrlEncodedFormEnreplacedy(params, HTTP.UTF_8);
addHeader(httpPost);
httpPost.setEnreplacedy(httpEnreplacedy);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEnreplacedy enreplacedy = httpResponse.getEnreplacedy();
ret = EnreplacedyUtils.toString(enreplacedy);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
19
Source : HttpClientConnection.java
with Apache License 2.0
from smallFive55
with Apache License 2.0
from smallFive55
@Override
public void sendRequest() throws IOException {
request.setEnreplacedy(new ByteArrayEnreplacedy(output.toByteArray()));
this.response = httpClient.execute(request);
}
19
Source : QueryBuilderCommon.java
with GNU General Public License v3.0
from SimplyUb
with GNU General Public License v3.0
from SimplyUb
/**
* @param command
* @param parameters
*
* @return
*
* example : MultichainQueryBuidlder.executeProcess(MultichainCommand .SENDTOADDRESS,
* "1EyXuq2JVrj4E3CpM9iNGNSqBpZ2iTPdwGKgvf {\"rdcoin\":0.01}"
* @throws MultichainException
*/
protected Object execute(CommandElt command, Object... parameters) throws MultichainException {
if (httpclient != null && httppost != null) {
try {
// Generate Mapping of calling arguments
Map<String, Object> enreplacedyValues = prepareMap(this.queryParameters, command, parameters);
// Generate the enreplacedy and initialize request
StringEnreplacedy rpcEnreplacedy = prepareRpcEnreplacedy(enreplacedyValues);
httppost.setEnreplacedy(rpcEnreplacedy);
// Execute the request and get the answer
return executeRequest();
} catch (IOException e) {
e.printStackTrace();
throw new MultichainException(null, e.toString());
}
} else {
throw new MultichainException("Initialization Problem", "MultiChainCommand not initialized, please specify ip, port, user and pwd !");
}
}
19
Source : TextraApiClient.java
with GNU General Public License v3.0
from miurahr
with GNU General Public License v3.0
from miurahr
private void authenticate(final String url, final String apiUsername, final String apiKey, final String apiSecret, final String text) {
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)).setRedirectStrategy(new LaxRedirectStrategy()).build();
requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIMEOUT).setSocketTimeout(SO_TIMEOUT).setRedirectsEnabled(true).build();
httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(apiKey, apiSecret);
List<BasicNameValuePair> postParameters = new ArrayList<>(5);
postParameters.add(new BasicNameValuePair("key", apiKey));
postParameters.add(new BasicNameValuePair("name", apiUsername));
postParameters.add(new BasicNameValuePair("type", "json"));
postParameters.add(new BasicNameValuePair("text", text));
try {
httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(postParameters, "UTF-8"));
} catch (UnsupportedEncodingException ex) {
LOGGER.info("Encoding error.");
}
try {
consumer.sign(httpPost);
} catch (OAuthMessageSignerException | OAuthExpectationFailedException | OAuthCommunicationException ex) {
LOGGER.info("OAuth error: " + ex.getMessage());
}
}
18
Source : NotificationService.java
with Apache License 2.0
from ZTO-Express
with Apache License 2.0
from ZTO-Express
public void sendDingdingGroup(AlertRuleConfig rule) {
HttpPost httppost = new HttpPost(rule.getAlertDingding());
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
Map<String, Object> map = new HashMap<>();
map.put("msgtype", "text");
Map<String, Object> content = new HashMap<>();
content.put("content", rule.getDescription());
map.put("text", content);
String errorMsg = JSON.toJSONString(map);
StringEnreplacedy se = new StringEnreplacedy(errorMsg, "utf-8");
httppost.setEnreplacedy(se);
HttpResponse response = null;
try {
response = httpClient.execute(httppost);
logger.info("send {} dingding group msg:{} ", rule.getRuleKey(), response.getStatusLine().getStatusCode());
} catch (IOException e) {
logger.error("send {} dingding group failed", rule.getRuleKey(), e);
} finally {
try {
if (null != response) {
IOUtils.closeQuietly(response.getEnreplacedy().getContent());
}
} catch (IOException e) {
logger.error("close error", e);
}
}
}
18
Source : HttpUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* Post stream
*
* @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, byte[] 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 (body != null) {
request.setEnreplacedy(new ByteArrayEnreplacedy(body));
}
return httpClient.execute(request);
}
18
Source : HttpUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* 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.setEnreplacedy(new StringEnreplacedy(body, "utf-8"));
}
return httpClient.execute(request);
}
18
Source : HttpClientUtils.java
with MIT License
from Zo3i
with MIT License
from Zo3i
/**
* http的post请求,增加异步请求头参数,传递json格式参数
*/
public static String ajaxPostJson(String url, String jsonString, String charset) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
// try {
// 解决中文乱码问题
StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(jsonString, charset);
stringEnreplacedy.setContentEncoding(charset);
stringEnreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(stringEnreplacedy);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
return executeRequest(httpPost, charset);
}
18
Source : HttpUtils.java
with Apache License 2.0
from zhuangjinming16
with Apache License 2.0
from zhuangjinming16
/**
* Post stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
}
if (body != null) {
request.setEnreplacedy(new ByteArrayEnreplacedy(body));
}
return httpClient.execute(request);
}
18
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* post提交json数据
* @param url
* @param jsonStr
* @return
*/
public static String doPostJson(String url, String jsonStr) {
String result = null;
HttpPost post = new HttpPost(url);
try {
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
post.setConfig(requestConfig);
post.addHeader("content-type", "application/json");
StringEnreplacedy myEnreplacedy = new StringEnreplacedy(jsonStr, "UTF-8");
post.setEnreplacedy(myEnreplacedy);
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
HttpEnreplacedy resEnreplacedy = response.getEnreplacedy();
if (resEnreplacedy != null) {
// String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy).getBytes("ISO_8859_1"),"GBK");
// String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy,"UTF-8"));
String respBody = new String(EnreplacedyUtils.toString(resEnreplacedy));
try {
result = respBody;
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
post.releaseConnection();
}
return result;
}
18
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* post方式提交表单(模拟用户登录请求)
*/
// BasicNameValuePair
public static String postForm(String url, List<NameValuePair> formparams) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
httppost.setConfig(requestConfig);
// 创建参数队列
// List<NameValuePair> formparams = new ArrayList<NameValuePair>();
// formparams.add(new BasicNameValuePair("username", "admin"));
// formparams.add(new BasicNameValuePair("preplacedword", "123456"));
UrlEncodedFormEnreplacedy uefEnreplacedy;
try {
uefEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, "UTF-8");
httppost.setEnreplacedy(uefEnreplacedy);
log.debug("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
String result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
log.debug("--------------------------------------");
log.debug("Response content: " + result);
log.debug("--------------------------------------");
return result;
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
18
Source : HttpUtils.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
* @return
*/
public static String post(String url, HashMap<String, String> map) {
String result = "";
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
httppost.setConfig(requestConfig);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
formparams.add(new BasicNameValuePair(key.toString(), map.get(key)));
}
UrlEncodedFormEnreplacedy uefEnreplacedy;
try {
uefEnreplacedy = new UrlEncodedFormEnreplacedy(formparams, "UTF-8");
httppost.setEnreplacedy(uefEnreplacedy);
// System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
// System.out.println("--------------------------------------");
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
log.info("Response content: " + result);
// System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
18
Source : locapiBaiduClientUtil.java
with Apache License 2.0
from zengfr
with Apache License 2.0
from zengfr
protected static locapiRespBody parse(locapiReq req) throws IOException {
StringBuffer sb = new StringBuffer();
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(api);
String reqStr = JSON.toJSONString(req);
StringEnreplacedy se = new StringEnreplacedy(reqStr);
System.out.println(reqStr);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
HttpEnreplacedy enreplacedy = resp.getEnreplacedy();
BufferedReader br = new BufferedReader(new InputStreamReader(enreplacedy.getContent()));
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
// 740 Failed to authenticate for api loc is forbidden.(服务被禁用,一般不会出现)
System.out.println(sb);
return JSON.parseObject(sb.toString(), locapiRespBody.clreplaced);
}
18
Source : WXPay.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
@SuppressWarnings("rawtypes")
@Override
public <T> Object refund(T t) throws Exception {
WXRefundParams wxRefundParams = (WXRefundParams) t;
String path = this.getClreplaced().getResource("/apiclient_cert.p12").getPath();
HttpClient client = HttpUtil.createSSL(path, WXPayUtil.MCHID);
Map<String, String> params = new HashMap<>();
params.put("appid", wxRefundParams.getAppId());
params.put("mch_id", wxRefundParams.getMchId());
params.put("nonce_str", wxRefundParams.genNonceStr());
params.put("out_trade_no", wxRefundParams.getOutTradeNo());
params.put("out_refund_no", wxRefundParams.getOutRefundNo());
params.put("total_fee", String.valueOf((int) (wxRefundParams.getTotalFee() * 100)));
params.put("refund_fee", String.valueOf((int) (wxRefundParams.getRefundFee() * 100)));
params.put("op_user_id", "1446023502");
String sign = WXPayUtil.getSign(params);
params.put("sign", sign);
String xmlstring = XMLUtil.toXml(params);
HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(xmlstring, "utf-8");
post.setEnreplacedy(postEnreplacedy);
String result = null;
HttpResponse response = client.execute(post);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
Map map = XMLUtil.getMapFromXML(result);
return map;
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendJSONPost(String url, String jsonData, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(jsonData, CHARSET_NAME);
postEnreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(postEnreplacedy);
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);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (Exception e) {
logger.error("http request error ", e);
} finally {
httpPost.abort();
}
return result;
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendPost(String url, String cnt) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(cnt, CHARSET_NAME);
httpPost.setEnreplacedy(postEnreplacedy);
httpPost.addHeader("Content-Type", "text/xml");
HttpClient client = HttpClients.createDefault();
try {
HttpResponse response = client.execute(httpPost);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (ConnectionPoolTimeoutException e) {
logger.error("message get throw ConnectionPoolTimeoutException(wait time out)");
} catch (ConnectTimeoutException e) {
logger.error("message get throw ConnectTimeoutException");
} catch (SocketTimeoutException e) {
logger.error("message get throw SocketTimeoutException");
} catch (Exception e) {
logger.error("message get throw Exception");
} finally {
httpPost.abort();
}
return result;
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String sendPost(String url, String cnt, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
StringEnreplacedy postEnreplacedy = new StringEnreplacedy(cnt, CHARSET_NAME);
httpPost.setEnreplacedy(postEnreplacedy);
httpPost.setHeader("Content-Type", "text/xml");
HttpClient client = HttpClients.createDefault();
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
httpPost.setHeader(k, v);
});
}
try {
HttpResponse response = client.execute(httpPost);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} catch (Exception e) {
logger.error("http request fail", e);
} finally {
httpPost.abort();
}
return result;
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
public static String postRequest(String url, List<NameValuePair> params) {
try {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
if (params != null) {
post.setEnreplacedy(new UrlEncodedFormEnreplacedy(params, CHARSET_NAME));
}
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEnreplacedy().getContent()));
StringBuilder res = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (Exception e) {
logger.error("message req error=" + url, e);
return null;
}
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
/**
* 表单提交post请求
*
* @param url
* @param params
* @return
*/
public static String sendPostForm(String url, List<NameValuePair> params) {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
try {
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(params, "UTF-8");
post.setEnreplacedy(enreplacedy);
HttpResponse response = client.execute(post);
String responseEnreplacedy = EnreplacedyUtils.toString(response.getEnreplacedy());
return responseEnreplacedy;
} catch (Exception e) {
logger.error("http请求失败 ----", e);
}
return null;
}
18
Source : HttpUtil.java
with Apache License 2.0
from yz-java
with Apache License 2.0
from yz-java
/**
* 表单提交post请求
*
* @param url
* @param params
* @return
*/
public static String sendPostForm(String url, List<NameValuePair> params, Map<String, String> headers) {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
if (headers != null && !headers.isEmpty()) {
headers.forEach((k, v) -> {
post.addHeader(k, v);
});
}
try {
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(params, "UTF-8");
post.setEnreplacedy(enreplacedy);
HttpResponse response = client.execute(post);
String responseEnreplacedy = EnreplacedyUtils.toString(response.getEnreplacedy());
return responseEnreplacedy;
} catch (Exception e) {
logger.error("http请求失败 ----", e);
}
return null;
}
18
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
// 测试需要登录的情况
@Test
public void login_sign() throws Exception {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
login(client);
String act = "plain_sign";
Map<String, Object> json = new HashMap<>();
json.put("name", "小明");
String req = S.json().toJson(json);
String sign = Encrypt.sign(req.getBytes(charset));
HttpPost post = new HttpPost(getUrl(act) + "?sign=" + sign);
StringEnreplacedy se = new StringEnreplacedy(req, charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
// 以下验证请求是否正确
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("hello 小明,来自admin的问候", ret);
}
18
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void base64() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "base64";
HttpPost post = new HttpPost(getUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
String req = Base64.getEncoder().encodeToString(S.json().toJson(json).replace("\"names\"", "names").getBytes(charset));
System.out.println("req:" + req);
StringEnreplacedy se = new StringEnreplacedy(req, charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = new String(Base64.getMimeDecoder().decode(EnreplacedyUtils.toString(resEnreplacedy)), charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
}
18
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void db_insert() throws IOException {
String charset = "UTF-8";
HttpClient client = HttpClientBuilder.create().build();
String act = "add";
HttpPost post = new HttpPost(getUrl(act));
List<DemoUser> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DemoUser obj = new DemoUser();
obj.setAge(r.nextInt(100));
obj.setName("名字" + r.nextInt());
obj.setId(r.nextLong());
list.add(obj);
}
Map<String, Object> json = new HashMap<>();
json.put("users", list);
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
System.out.println(line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
System.out.println(ret);
replacedert.replacedertEquals(list.size() + "", ret);
}
18
Source : PlainClientTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void plain() throws IOException {
String charset = "GBK";
HttpClient client = HttpClientBuilder.create().build();
String act = "echo";
HttpPost post = new HttpPost(getUrl(act));
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
HttpResponse resp = client.execute(post);
String line = resp.getStatusLine().toString();
replacedert.replacedertEquals("HTTP/1.1 200 OK", line);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
}
18
Source : HttpPressTest.java
with Apache License 2.0
from youtongluan
with Apache License 2.0
from youtongluan
@Test
public void test() throws IOException, InterruptedException {
String charset = "utf-8";
HttpClient client = HttpClientBuilder.create().setMaxConnTotal(5000).setMaxConnPerRoute(1000).build();
ExecutorService executor = Executors.newFixedThreadPool(500);
HttpPost post = new HttpPost("http://localhost:8080/rest/echo");
Map<String, Object> json = new HashMap<>();
json.put("echo", "你好!!!");
json.put("names", Arrays.asList("小明", "小张"));
StringEnreplacedy se = new StringEnreplacedy(S.json().toJson(json), charset);
post.setEnreplacedy(se);
System.out.println("开始压测,请耐心等待10秒左右。。。");
long begin = System.currentTimeMillis();
int count = 100000;
AtomicLong totalRT = new AtomicLong();
AtomicLong success = new AtomicLong();
for (int i = 0; i < count; i++) {
executor.execute(() -> {
try {
long b2 = System.currentTimeMillis();
HttpResponse resp = client.execute(post);
HttpEnreplacedy resEnreplacedy = resp.getEnreplacedy();
totalRT.addAndGet(System.currentTimeMillis() - b2);
String ret = EnreplacedyUtils.toString(resEnreplacedy, charset);
replacedert.replacedertEquals("[\"你好!!! 小明\",\"你好!!! 小张\"]", ret);
success.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
}
});
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
long time = System.currentTimeMillis() - begin;
replacedert.replacedertEquals(count, success.get());
System.out.println(count + "次http请求总耗时:" + time + "ms,平均每秒请求数:" + (count * 1000d / time));
System.out.println("平均每个请求耗时:" + totalRT.get() / count + "ms");
}
18
Source : HttpPostDeliverService.java
with MIT License
from Yirendai
with MIT License
from Yirendai
public boolean deliver(final List<Span> spanList) {
boolean ret = false;
if (CollectionUtils.isEmpty(spanList)) {
LOGGER.error("spanList is Empty!");
ret = false;
} else {
if (httpClient == null || httpPost == null) {
LOGGER.error("httpClient({}) or httpPost({}) is null", httpClient, httpPost);
ret = false;
} else {
final long startTime = System.currentTimeMillis();
final int spanSize = spanList.size();
final String spanListJson = JSON.toJSONString(spanList);
final StringEnreplacedy postingString = new StringEnreplacedy(spanListJson, "utf-8");
httpPost.setEnreplacedy(postingString);
httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
public void completed(final HttpResponse response) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[push({})] [http_status:200] [spanSize:{}] [{}ms]", spanListJson, spanSize, (System.currentTimeMillis() - startTime));
}
}
public void failed(final Exception ex) {
LOGGER.error("[push({})] [{}] [error:{}]", httpPost.getURI(), spanListJson, ex);
}
public void cancelled() {
LOGGER.error("[push({})] [http_status:cancelled] [{}ms]", spanListJson, (System.currentTimeMillis() - startTime));
}
});
ret = true;
}
}
return ret;
}
18
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
/**
* 设置表单参数 主要给post使用
*
* @param param
* @param httpPost
* @throws UnsupportedEncodingException
*/
private static void setFormParam(Map<String, String> param, HttpPost httpPost) throws UnsupportedEncodingException {
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEnreplacedy enreplacedy = new UrlEncodedFormEnreplacedy(paramList);
httpPost.setEnreplacedy(enreplacedy);
}
}
18
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
/**
* 设置json参数
*
* @param json
* @param httpPost
*/
private static void setJsonParam(String json, HttpPost httpPost) {
StringEnreplacedy enreplacedy = new StringEnreplacedy(json, ContentType.APPLICATION_JSON);
httpPost.setEnreplacedy(enreplacedy);
}
18
Source : HttpClientTest.java
with Apache License 2.0
from yametech
with Apache License 2.0
from yametech
@org.junit.Test
public void test1() {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://fanyi.youdao.com/openapi.do");
try {
List<BasicNameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("keyfrom", "siwuxie095-test"));
list.add(new BasicNameValuePair("key", "2140200403"));
list.add(new BasicNameValuePair("type", "data"));
list.add(new BasicNameValuePair("doctype", "xml"));
list.add(new BasicNameValuePair("version", "1.1"));
list.add(new BasicNameValuePair("q", "welcome"));
post.setEnreplacedy(new UrlEncodedFormEnreplacedy(list, "UTF-8"));
HttpResponse response = client.execute(post);
HttpEnreplacedy enreplacedy = response.getEnreplacedy();
String result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
System.out.println(result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
18
Source : HttpClientImpl.java
with GNU Lesser General Public License v3.0
from xkcoding
with GNU Lesser General Public License v3.0
from xkcoding
/**
* POST 请求
*
* @param url URL
* @param params form 参数
* @param header 请求头
* @param encode 是否需要 url encode
* @return 结果
*/
@Override
public String post(String url, Map<String, String> params, HttpHeader header, boolean encode) {
HttpPost httpPost = new HttpPost(url);
if (MapUtil.isNotEmpty(params)) {
List<NameValuePair> form = new ArrayList<>();
MapUtil.forEach(params, (k, v) -> form.add(new BasicNameValuePair(k, v)));
httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(form, Constants.DEFAULT_ENCODING));
}
if (header != null) {
MapUtil.forEach(header.getHeaders(), httpPost::addHeader);
}
return this.exec(httpPost);
}
18
Source : HttpClientImpl.java
with GNU Lesser General Public License v3.0
from xkcoding
with GNU Lesser General Public License v3.0
from xkcoding
/**
* POST 请求
*
* @param url URL
* @param data JSON 参数
* @param header 请求头
* @return 结果
*/
@Override
public String post(String url, String data, HttpHeader header) {
HttpPost httpPost = new HttpPost(url);
if (StringUtil.isNotEmpty(data)) {
StringEnreplacedy enreplacedy = new StringEnreplacedy(data, Constants.DEFAULT_ENCODING);
enreplacedy.setContentEncoding(Constants.DEFAULT_ENCODING.displayName());
enreplacedy.setContentType(Constants.CONTENT_TYPE_JSON);
httpPost.setEnreplacedy(enreplacedy);
}
if (header != null) {
MapUtil.forEach(header.getHeaders(), httpPost::addHeader);
}
return this.exec(httpPost);
}
18
Source : CheckMessageUtil.java
with MIT License
from Xin-Felix
with MIT License
from Xin-Felix
public static Boolean checkMessage(String content, WXMessage wxMessage) {
String s = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxMessage.getWxId() + "&secret=" + wxMessage.getWxSecret());
AccessToken accessToken = JsonUtils.jsonToPojo(s, AccessToken.clreplaced);
String token = accessToken.getAccess_token();
String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + token;
String param = "{\"content\":\"" + content + "\"}";
// 创建client和post对象
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
// json形式
post.addHeader("content-type", "image");
// json字符串以实体的实行放到post中
post.setEnreplacedy(new StringEnreplacedy(param, Charset.forName("utf-8")));
HttpResponse response = null;
try {
// 获得response对象
response = client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
System.out.println("请求返回不正确");
}
String result = "";
try {
// 获得字符串形式的结果
result = EnreplacedyUtils.toString(response.getEnreplacedy());
} catch (Exception e) {
e.printStackTrace();
}
CheckMessage checkMessage = JsonUtils.jsonToPojo(result, CheckMessage.clreplaced);
if (checkMessage.getErrcode().equals(87014)) {
return true;
} else {
return false;
}
}
18
Source : HttpClient.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
public FullHttpResponse post(FilterContext ctx, String url, byte[] body, Map<String, String> headers, int timeOut) {
ctx.getAttachments().put("param", new String(body));
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).build();
HttpPost post = new HttpPost(url);
headers.entrySet().stream().forEach(it -> {
if (!it.getKey().equals("Host")) {
post.setHeader(it.getKey(), it.getValue());
}
});
post.setEnreplacedy(new ByteArrayEnreplacedy(body));
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEnreplacedy enreplacedy = null;
String responseContent = null;
String callId = UUID.randomUUID().toString();
try {
httpClient = HttpClients.createDefault();
post.setConfig(requestConfig);
clientMap.put(callId, httpClient);
response = httpClient.execute(post);
enreplacedy = response.getEnreplacedy();
responseContent = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
logger.debug("----------> http post url:{} body:{} result:{}", url, body, responseContent);
ByteBuf buf = ByteBufUtils.createBuf(ctx, responseContent, configService.isAllowDirectBuf());
FullHttpResponse r = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.getStatusLine().getStatusCode()), buf);
Arrays.stream(response.getAllHeaders()).forEach(it -> r.headers().add(it.getName(), it.getValue()));
return HttpResponseUtils.create(r);
} catch (Throwable e) {
logger.warn(e.getMessage());
return HttpResponseUtils.create(Result.fail(GeneralCodes.InternalError, Msg.msgFor500, e.getMessage()));
} finally {
clientMap.remove(callId);
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
18
Source : HttpUtils.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
public static HttpResult post(String url, Map<String, String> headers, String params, int timeout) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(// CS 数据交互时间
timeout).setConnectTimeout(// 指建立连接的超时时间
timeout).build();
HttpResult result = null;
Gson gson = new Gson();
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpEnreplacedy enreplacedy = null;
String responseContent = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost request = new HttpPost(uriBuilder.build().toASCIIString());
// request.setHeader("Content-Type", "application/json");
// request.setHeader("Accept", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
request.setConfig(requestConfig);
StringEnreplacedy requestEnreplacedy = new StringEnreplacedy(params, "UTF-8");
request.setEnreplacedy(requestEnreplacedy);
response = httpClient.execute(request);
int state = response.getStatusLine().getStatusCode();
if (state != HttpStatus.SC_OK) {
log.error("[HttpUtils.post]: failed to request: {}, headers: {}, params: {}, response status: {}", url, headers, params, state);
return HttpResult.fail(state);
}
enreplacedy = response.getEnreplacedy();
responseContent = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
result = HttpResult.success(HttpStatus.SC_OK, responseContent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
18
Source : ContextTest.java
with MIT License
from xiantang
with MIT License
from xiantang
@Test
public void testHttpServerPostCanHandleCertainServlet() throws Exception {
int availablePort = NetUtils.getAvailablePort();
Map<String, ServletWrapper> mapper = new HashMap<>();
String body = "{\n" + " \"Name\":\"李念\",\n" + " \"Stature\":\"163cm\",\n" + " \"Birthday\":\"1985年5月30日\",\n" + " \"Birthplace\":\"湖北省荆门市京山县\",\n" + " \"Info\":\"喜欢电视剧版《蜗居》中李念扮演的郭海藻,为六六的小说《蜗居》中的女主角之一,郭海萍的妹妹。\",\n" + " \"Still\":\"https://cdn.www.sojson.com/study/linian.jpg\"\n" + "}";
Servlet servlet = (request, response) -> {
OutputStream outputStream = response.getResponseOutputStream();
String body1 = request.getBody();
outputStream.write(body1.getBytes());
};
mapper.put("/test", new ServletWrapper("", "/test", "aaa", null, servlet.getClreplaced(), servlet));
Configuration configuration = new Configuration(availablePort, 3, mapper);
Context context = new Context("jarName", configuration);
context.init();
context.start();
CloseableHttpClient httpclient = HttpClients.createDefault();
StringEnreplacedy requestEnreplacedy = new StringEnreplacedy(body, ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://localhost:" + availablePort + "/test");
postMethod.setEnreplacedy(requestEnreplacedy);
HttpResponse rawResponse = httpclient.execute(postMethod);
HttpEnreplacedy enreplacedy = rawResponse.getEnreplacedy();
String actual = EnreplacedyUtils.toString(enreplacedy, Charsets.UTF_8);
replacedertEquals(body, actual);
}
18
Source : ApacheHttpClient.java
with Apache License 2.0
from xiancloud
with Apache License 2.0
from xiancloud
@Override
public String post(String body) throws ConnectTimeoutException, SocketTimeoutException {
/*
* LOG.info(String.format(
* "httpClient获取到的header: %s ; httpClient获取到的body:%s ", headers,
* body));
*/
if (client == null) {
return INIT_FAIL;
}
HttpPost httpPost = new HttpPost(url);
httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
String responseContent;
try {
StringEnreplacedy enreplacedy = new StringEnreplacedy(body == null ? "" : body, "utf-8");
enreplacedy.setContentEncoding("utf-8");
enreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(enreplacedy);
httpPost.setConfig(requestConfig);
HttpResponse httpResponse = client.execute(httpPost);
responseContent = EnreplacedyUtils.toString(httpResponse.getEnreplacedy(), "utf-8");
} catch (ConnectTimeoutException | SocketTimeoutException connectOrReadTimeout) {
throw connectOrReadTimeout;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
httpPost.releaseConnection();
}
return responseContent;
}
18
Source : HttpClientUtil.java
with Apache License 2.0
from xfyun
with Apache License 2.0
from xfyun
/**
* 发送post请求
*
* @param url
* @param maps
* @return
*/
public String sendHttpPost(String url, Map<String, String> maps) {
// 创建httpClient对象
HttpPost httpPost = new HttpPost(url);
// 创建参数队列,装填参数
List<NameValuePair> nameValuePairs = new ArrayList<>();
// 如果map不为空的时候遍历map
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
// 设置参数到请求的对象中去
httpPost.setEnreplacedy(new UrlEncodedFormEnreplacedy(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return this.sendHttpPost(httpPost);
}
18
Source : HttpClientUtil.java
with Apache License 2.0
from xfyun
with Apache License 2.0
from xfyun
/**
* 发送post请求
*
* @param url
* @param params
* @return
*/
public String sendHttpPost(String url, String params) {
HttpPost httpPost = new HttpPost(url);
try {
// 设置参数
StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(params, "UTF-8");
stringEnreplacedy.setContentType("application/x-www-form-urlencoded");
httpPost.setEnreplacedy(stringEnreplacedy);
} catch (Exception e) {
e.printStackTrace();
}
return this.sendHttpPost(httpPost);
}
18
Source : HttpClientUtil.java
with Apache License 2.0
from xfyun
with Apache License 2.0
from xfyun
/**
* 发送post请求,参数为json
*
* @param url
* @param json
* @return
*/
public String sendHttpPostForJson(String url, String json) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
// 设置参数
StringEnreplacedy stringEnreplacedy = new StringEnreplacedy(json, "utf-8");
stringEnreplacedy.setContentType("application/json");
httpPost.setEnreplacedy(stringEnreplacedy);
return this.sendHttpPost(httpPost);
}
18
Source : ElasticSearchUtil.java
with Apache License 2.0
from xaecbd
with Apache License 2.0
from xaecbd
public static String httpPost(String url, HttpEnreplacedy enreplacedy) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEnreplacedy(enreplacedy);
return getResult(httpPost);
}
18
Source : Report.java
with Apache License 2.0
from xaecbd
with Apache License 2.0
from xaecbd
protected static String httpPost(String url, HttpEnreplacedy enreplacedy) {
HttpPost httpPost = new HttpPost(url);
httpPost.setEnreplacedy(enreplacedy);
return getResult(httpPost);
}
18
Source : HttpClientUtil.java
with Apache License 2.0
from x-ream
with Apache License 2.0
from x-ream
public static String post(String url, Object param, List<KV> hearderList, int connectTimeoutMS, int socketTimeoutMS, CloseableHttpClient httpclient) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeoutMS).setConnectTimeout(connectTimeoutMS).setConnectionRequestTimeout(1000).build();
httpPost.setConfig(requestConfig);
if (hearderList != null) {
for (KV kv : hearderList) {
httpPost.addHeader(kv.getK(), kv.getV().toString());
}
}
String json = "";
if (param != null) {
json = JsonX.toJson(param);
}
HttpEnreplacedy enreplacedy = null;
String result = null;
try {
enreplacedy = new ByteArrayEnreplacedy(json.getBytes("UTF-8"));
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
httpPost.setEnreplacedy(enreplacedy);
logger.info("executing request " + httpPost.getURI());
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
enreplacedy = response.getEnreplacedy();
if (enreplacedy != null) {
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
logger.info("Response content: " + result);
}
} finally {
response.close();
}
} catch (HttpHostConnectException hce) {
hce.printStackTrace();
String str = "org.apache.http.conn.HttpHostConnectException: Connect to " + url + " failed: Connection refused: connect";
throw new RuntimeException(str);
} catch (ConnectTimeoutException cte) {
cte.printStackTrace();
String str = "org.apache.http.conn.ConnectTimeoutException: Connect to " + url + " failed: Connection timeout: connect";
throw new RuntimeException(str);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException(ExceptionUtil.getMessage(ioe));
} catch (Exception e) {
throw e;
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
18
Source : NetRequestUtils.java
with MIT License
from wx-chevalier
with MIT License
from wx-chevalier
/**
* 发送Post 请求
*/
private static String post(String url, String requestBody) {
log.info("发送 post 请求: url = {} requestBody={} ", url, requestBody);
HttpPost postClient = new HttpPost(url);
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(requestBody.getBytes(Charset.defaultCharset()));
postClient.setEnreplacedy(enreplacedy);
postClient.setConfig(requestConfig);
return send(postClient);
}
18
Source : SortTest.java
with Apache License 2.0
from wso2-incubator
with Apache License 2.0
from wso2-incubator
/**
* Create groups for testing purpose.
* @return
* @throws ComplianceException
* @throws GeneralComplianceException
*/
private HashMap<String, String> CreateTestsGroups() throws ComplianceException, GeneralComplianceException {
ArrayList<String> definedGroups = new ArrayList<>();
definedGroups.add("{\"displayName\": \"EYtXcD41\"}");
definedGroups.add("{\"displayName\": \"BktqER42\"}");
definedGroups.add("{\"displayName\": \"ZwLtOP43\"}");
HttpPost method = new HttpPost(groupURL);
// create groups
HttpClient client = HTTPClient.getHttpClient();
method = (HttpPost) HTTPClient.setAuthorizationHeader(complianceTestMetaDataHolder, method);
method.setHeader("Accept", "application/json");
method.setHeader("Content-Type", "application/json");
HttpResponse response = null;
String responseString = "";
String headerString = "";
String responseStatus = "";
ArrayList<String> subTests = new ArrayList<>();
for (int i = 0; i < 3; i++) {
try {
// create the group
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(definedGroups.get(i).getBytes("UTF-8"));
method.setEnreplacedy(enreplacedy);
response = client.execute(method);
// Read the response body.
responseString = new BasicResponseHandler().handleResponse(response);
responseStatus = String.valueOf(response.getStatusLine().getStatusCode());
if (responseStatus.equals("201")) {
// obtain the schema corresponding to group
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema();
JSONDecoder jsonDecoder = new JSONDecoder();
Group group = null;
try {
group = (Group) jsonDecoder.decodeResource(responseString, schema, new Group());
} catch (BadRequestException | CharonException | InternalErrorException e) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Sort Groups", "Could not decode the server response of groups create.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
groupIDs.put(group.getId(), group.getDisplayName());
}
} catch (Exception e) {
// Read the response body.
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
headerString += header.getName() + " : " + header.getValue() + "\n";
}
responseStatus = response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Sort Groups", "Could not create default groups at url " + groupURL, ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
return groupIDs;
}
18
Source : PaginationTest.java
with Apache License 2.0
from wso2-incubator
with Apache License 2.0
from wso2-incubator
/**
* Create groups fro testing purpose.
* @return
* @throws ComplianceException
* @throws GeneralComplianceException
*/
private ArrayList<String> CreateTestsGroups() throws ComplianceException, GeneralComplianceException {
ArrayList<String> definedGroups = new ArrayList<>();
definedGroups.add("{\"displayName\": \"EYtXcD11\"}");
definedGroups.add("{\"displayName\": \"BktqER12\"}");
definedGroups.add("{\"displayName\": \"ZwLtOP13\"}");
HttpPost method = new HttpPost(groupURL);
// create groups
HttpClient client = HTTPClient.getHttpClient();
method = (HttpPost) HTTPClient.setAuthorizationHeader(complianceTestMetaDataHolder, method);
method.setHeader("Accept", "application/json");
method.setHeader("Content-Type", "application/json");
HttpResponse response = null;
String responseString = "";
String headerString = "";
String responseStatus = "";
ArrayList<String> subTests = new ArrayList<>();
for (int i = 0; i < 3; i++) {
try {
// create the group
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(definedGroups.get(i).getBytes("UTF-8"));
method.setEnreplacedy(enreplacedy);
response = client.execute(method);
// Read the response body.
responseString = new BasicResponseHandler().handleResponse(response);
responseStatus = String.valueOf(response.getStatusLine().getStatusCode());
if (responseStatus.equals("201")) {
// obtain the schema corresponding to group
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema();
JSONDecoder jsonDecoder = new JSONDecoder();
Group group = null;
try {
group = (Group) jsonDecoder.decodeResource(responseString, schema, new Group());
} catch (BadRequestException | CharonException | InternalErrorException e) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Paginate Groups", "Could not decode the server response of groups create.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
groupIDs.add(group.getId());
}
} catch (Exception e) {
// Read the response body.
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
headerString += header.getName() + " : " + header.getValue() + "\n";
}
responseStatus = response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Paginate Groups", "Could not create default groups at url " + groupURL, ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
return groupIDs;
}
18
Source : PaginationTest.java
with Apache License 2.0
from wso2-incubator
with Apache License 2.0
from wso2-incubator
/**
* Create users for testing purpose.
* @return
* @throws ComplianceException
* @throws GeneralComplianceException
*/
private ArrayList<String> CreateTestsUsers() throws ComplianceException, GeneralComplianceException {
ArrayList<String> definedUsers = new ArrayList<>();
definedUsers.add("{\"preplacedword\": \"7019asd81\",\"userName\": \"AbrTkAA11\"}");
definedUsers.add("{\"preplacedword\": \"7019asd82\",\"userName\": \"UttEdHt12\"}");
definedUsers.add("{\"preplacedword\": \"7019asd83\",\"userName\": \"KKTQwhr13\"}");
HttpPost method = new HttpPost(usersURL);
// create users
HttpClient client = HTTPClient.getHttpClient();
method = (HttpPost) HTTPClient.setAuthorizationHeader(complianceTestMetaDataHolder, method);
method.setHeader("Accept", "application/json");
method.setHeader("Content-Type", "application/json");
HttpResponse response = null;
String responseString = "";
String headerString = "";
String responseStatus = "";
ArrayList<String> subTests = new ArrayList<>();
for (int i = 0; i < 3; i++) {
try {
// create the group
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(definedUsers.get(i).getBytes("UTF-8"));
method.setEnreplacedy(enreplacedy);
response = client.execute(method);
// Read the response body.
responseString = new BasicResponseHandler().handleResponse(response);
responseStatus = String.valueOf(response.getStatusLine().getStatusCode());
if (responseStatus.equals("201")) {
// obtain the schema corresponding to group
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
JSONDecoder jsonDecoder = new JSONDecoder();
User user = null;
try {
user = (User) jsonDecoder.decodeResource(responseString, schema, new User());
} catch (BadRequestException | CharonException | InternalErrorException e) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Pagination Users", "Could not decode the server response of users create.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
userIDs.add(user.getId());
}
} catch (Exception e) {
// Read the response body.
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
headerString += header.getName() + " : " + header.getValue() + "\n";
}
responseStatus = response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "Pagination Users", "Could not create default users at url " + usersURL, ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
return userIDs;
}
18
Source : ListTest.java
with Apache License 2.0
from wso2-incubator
with Apache License 2.0
from wso2-incubator
/**
* Create test groups.
* @return
* @throws ComplianceException
* @throws GeneralComplianceException
*/
private ArrayList<String> CreateTestsGroups() throws ComplianceException, GeneralComplianceException {
ArrayList<String> definedGroups = new ArrayList<>();
definedGroups.add("{\"displayName\": \"EYtXcD21\"}");
definedGroups.add("{\"displayName\": \"BktqER22\"}");
definedGroups.add("{\"displayName\": \"ZwLtOP23\"}");
HttpPost method = new HttpPost(groupURL);
// create groups
HttpClient client = HTTPClient.getHttpClient();
method = (HttpPost) HTTPClient.setAuthorizationHeader(complianceTestMetaDataHolder, method);
method.setHeader("Accept", "application/json");
method.setHeader("Content-Type", "application/json");
HttpResponse response = null;
String responseString = "";
String headerString = "";
String responseStatus = "";
ArrayList<String> subTests = new ArrayList<>();
for (int i = 0; i < 3; i++) {
try {
// create the group
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(definedGroups.get(i).getBytes("UTF-8"));
method.setEnreplacedy(enreplacedy);
response = client.execute(method);
// Read the response body.
responseString = new BasicResponseHandler().handleResponse(response);
responseStatus = String.valueOf(response.getStatusLine().getStatusCode());
if (responseStatus.equals("201")) {
// obtain the schema corresponding to group
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema();
JSONDecoder jsonDecoder = new JSONDecoder();
Group group = null;
try {
group = (Group) jsonDecoder.decodeResource(responseString, schema, new Group());
} catch (BadRequestException | CharonException | InternalErrorException e) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "List Groups", "Could not decode the server response of groups create.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
groupIDs.add(group.getId());
}
} catch (Exception e) {
// Read the response body.
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
headerString += header.getName() + " : " + header.getValue() + "\n";
}
responseStatus = response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "List Groups", "Could not create default groups at url " + groupURL, ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
return groupIDs;
}
18
Source : ListTest.java
with Apache License 2.0
from wso2-incubator
with Apache License 2.0
from wso2-incubator
/**
* Create test users.
* @return
* @throws ComplianceException
* @throws GeneralComplianceException
*/
private ArrayList<String> CreateTestsUsers() throws ComplianceException, GeneralComplianceException {
ArrayList<String> definedUsers = new ArrayList<>();
definedUsers.add("{\"preplacedword\": \"7019asd81\",\"userName\": \"AbrTkAA21\"}");
definedUsers.add("{\"preplacedword\": \"7019asd82\",\"userName\": \"UttEdHt22\"}");
definedUsers.add("{\"preplacedword\": \"7019asd83\",\"userName\": \"KKTQwhr23\"}");
HttpPost method = new HttpPost(usersURL);
// create users
HttpClient client = HTTPClient.getHttpClient();
method = (HttpPost) HTTPClient.setAuthorizationHeader(complianceTestMetaDataHolder, method);
method.setHeader("Accept", "application/json");
method.setHeader("Content-Type", "application/json");
HttpResponse response = null;
String responseString = "";
String headerString = "";
String responseStatus = "";
ArrayList<String> subTests = new ArrayList<>();
for (int i = 0; i < 3; i++) {
try {
// create the group
HttpEnreplacedy enreplacedy = new ByteArrayEnreplacedy(definedUsers.get(i).getBytes("UTF-8"));
method.setEnreplacedy(enreplacedy);
response = client.execute(method);
// Read the response body.
responseString = new BasicResponseHandler().handleResponse(response);
responseStatus = String.valueOf(response.getStatusLine().getStatusCode());
if (responseStatus.equals("201")) {
// obtain the schema corresponding to group
SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
JSONDecoder jsonDecoder = new JSONDecoder();
User user = null;
try {
user = (User) jsonDecoder.decodeResource(responseString, schema, new User());
} catch (BadRequestException | CharonException | InternalErrorException e) {
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "List Users", "Could not decode the server response of users create.", ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
userIDs.add(user.getId());
}
} catch (Exception e) {
// Read the response body.
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
headerString += header.getName() + " : " + header.getValue() + "\n";
}
responseStatus = response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
throw new GeneralComplianceException(new TestResult(TestResult.ERROR, "List Users", "Could not create default users at url " + usersURL, ComplianceUtils.getWire(method, responseString, headerString, responseStatus, subTests)));
}
}
return userIDs;
}
See More Examples