importjava.io.BufferedReader;importjava.io.DataOutputStream;importjava.io.InputStreamReader;.HttpURLConnection;.URL;importjava.util.List;importjava.util.Map;/*** http 工具类*/
public classHttpUtil {public staticString post(String requestUrl, String accessToken, String params)throwsException {
String contentType= "application/x-www-form-urlencoded";returnHttpUtil.post(requestUrl, accessToken, contentType, params);
}public staticString post(String requestUrl, String accessToken, String contentType, String params)throwsException {
String encoding= "UTF-8";if (requestUrl.contains("nlp")) {
encoding= "GBK";
}returnHttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
}public staticString post(String requestUrl, String accessToken, String contentType, String params, String encoding)throwsException {
String url= requestUrl + "?access_token=" +accessToken;returnHttpUtil.postGeneralUrl(url, contentType, params, encoding);
}public staticString postGeneralUrl(String generalUrl, String contentType, String params, String encoding)throwsException {
URL url= newURL(generalUrl);//打开和URL之间的连接
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");//设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);//得到请求的输出流对象
DataOutputStream out = newDataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();//建立实际的连接
connection.connect();//获取所有响应头字段
Map> headers =connection.getHeaderFields();//遍历所有的响应头字段
for(String key : headers.keySet()) {//System.err.println(key + "--->" + headers.get(key));
}//定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in= newBufferedReader(newInputStreamReader(connection.getInputStream(), encoding));
String result= "";
String getLine;while ((getLine = in.readLine()) != null) {
result+=getLine;
}
in.close();//System.err.println("result:" + result);
returnresult;
}
}
如果觉得《植物识别库java_基于百度api的植物图片识别 人脸检测 人脸对比。》对你有帮助,请点赞、收藏,并留下你的观点哦!