需求
将一个请求转换为java代码去执行,想要执行的命令格式如下:
curl -X POST -H "Content-Type: application/json" \
https://xxxxx.cn/xx/xx \
-d '{
"msg_type":"text",
"content":{
"text":"request example"
}
}'
代码实现
/**
* 发起请求
* @param url :想要请求的地址
* @param str :想要传递的内容
* @throws IOException
*/
public void httpPost(String url,String str) throws IOException {
HttpClient httpClient = new HttpClient();
httpClient.getParams().setContentCharset("UTF-8");
PostMethod method = new PostMethod(url);
RequestEntity entity = new StringRequestEntity(str,"application/json","UTF-8");
method.setRequestEntity(entity);
httpClient.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
//下面将stream转换为String
StringBuffer sb = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
char[] b = new char[4096];
for(int n; (n = isr.read(b)) != -1;) {
sb.append(new String(b, 0, n));
}
String returnStr = sb.toString();
System.out.println(returnStr);
}