泛微oa对接企业微信api时在学习如何使用java发送网络请求.由于不会在泛微里加jar包,所以我放弃了okhttp3来发送网络请求,使用了java的原生类java.net来发送网络请求.
请求的代码原型我是用webapi中的代码示例中拉出来的,现在的代码是在其基础上修改的
参考链接:Http——HttpURLConnection详解 - 曹伟雄 - 博客园 (cnblogs.com)
1.get请求
private static String doGet(String httpUrl) {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedReader bufferedReader = null;
String result = null;
try {
URL url = new URL(httpUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(6000);
connection.connect();
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp;
while ((temp = bufferedReader.readLine()) != null) {
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (null != connection) {
connection.disconnect();
}
}
return result;
}
2.post请求
public static String doPost(String httpUrl, String params) {
// HttpURLConnection connection=null;
// OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
// BufferedReader bufferedReader = null;
String result= null;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type","application/json");
// 需要转换编码格式,否则输出到企业微信时是乱码格式
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8"));
// writer.write(params);
// outputStream.write(params.getBytes());
outputStreamWriter.write(params);
outputStreamWriter.flush();
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
StringBuffer sbf = new StringBuffer();
String temp;
while ((temp = bufferedReader.readLine()) !=null){
sbf.append(temp);
sbf.append(System.getProperty("line.separator"));
}
result=sbf.toString();
}
}catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (inputStream != null) {
try {
inputStream.close();
outputStreamWriter.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return result;
}