将一个请求转换为java代码去执行,想要执行的命令格式如下:
curl -X POST -H "Content-Type: application/json" https://xxxxx.cn/xx/xx -d '{ "msg_type":"text", "content":{ "text":"request example" } }'代码实现
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); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)