用于Http请求使用
使用场景:参数为body,并需要设置Header头部信息
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
* @description: http请求工具类
* @author: Cc
* @data: 2020/6/10 11:08
*/
public class HttpsUtils {
//请求方法
public static JSONObject httpsRequest(String requestUrl, String requestMethod, JSONObject paramJson) {
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
InputStream inputStream = null;
HttpURLConnection conn = null;
try {
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
Map<String, String> header = SignUtil.getHeader();
//设置Header
for (Map.Entry<String, String> map :header.entrySet()){
conn.setRequestProperty(map.getKey(),map.getValue());
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type", "application/json;charset=utf-8");
//添加参数
OutputStream outputStream = conn.getOutputStream();
outputStream.write(paramJson.toString().getBytes("UTF-8"));
outputStream.close();
// 从输入流读取返回内容
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer mess = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
mess.append(str);
}
return JSONObject.parseObject(mess.toString());
} catch (ConnectException ce) {
System.out.println("连接超时:{}" + ce);
} catch (Exception e) {
System.out.println("https请求异常:{}" + e);
}finally {
try {
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("ottCode","0033d8e5e36745d38c7e0e73fcb4883c");
JSONObject post = HttpsUtils.httpsRequest("https://xxx/api/authc/ottAuthor", "POST", jsonObject);
JSONObject data = post.getJSONObject("data");
System.out.println(post);
}
}
返回结果:
{“code”:1,“data”:{“phone”:“138xxxxx”,“avatar”:“https://www.baidu.com”,“userId”:“0033d8e5e36745d38c7e0e73fcb4883c”,“coin”:0},“message”:“操作成功”}