Commit bfa2368b authored by 王炜's avatar 王炜

调整电子合同请求中台http,预防隐藏问题

parent d9edbca1
package com.hand.elecon.httpost;
/**
* 修复原代码中连接未关闭等问题
*
* @author Administrator 2023/06/15 14:55
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class EleFileUpHttpPost {
public static int httpStatus=200;
public static void main(String[] args)
{
String token= EleFileUpHttpPost.post("https://cmmpdev.honglinglease.com.cn/hl_cm_dev/oauth/token?client_id=client2&client_secret=secret&grant_type=password&username=admin&password=admin",null,null);
System.out.println(token);
}
public static String post(String strURL, String params, String token)
{
BufferedReader reader = null;
HttpURLConnection connection=null;
OutputStream os = null;
InputStream is = null;
try
{
URL url = new URL(strURL);
connection = (HttpURLConnection)url.openConnection();
if ((token != null) && (token != "")) {
token = "Bearer " + token;
connection.setRequestProperty("Authorization", token);
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
//设置连接超时时间(必须)
connection.setConnectTimeout(150000);
//设置读取超时时间(必须)
connection.setReadTimeout(150000);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
os = connection.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
out.append(params);
out.flush();
out.close();
if (connection.getResponseCode() == httpStatus) {
is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String res = "";
String line;
while ((line = reader.readLine()) != null) {
res = res + line;
}
reader.close();
return res;
}else{
return "error";
}
}
catch (IOException e) {
e.printStackTrace();
}finally {
//关闭连接
// 关闭连接的顺序,如果connection.disconnect()放在stream和reader关闭后调用
// 那么将不会关闭客户端和服务器的socket连接,如此会导致脚本结束后,连接强制断开
// 所以,如果不需要缓存socket,那么应该首先断开socket连接
connection.disconnect();
//关闭其他连接
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment