Commit e037f7bb authored by 张俊's avatar 张俊

提取公共方法

parent 0fee3102
package net.cdkj.gjj.adapter.domain;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
public class HttpUtil {
/**
* 获取请求入参数据
*/
public static String getReqData(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
json.append(line);
}
} catch (Exception e) {
System.out.println(e);
}
String str = json.toString();
System.out.println("要发送给第三方的公积金系统服务报文:" + str);
return str;
}
/**
* 发起 post 请求,并对出参进行解压缩
*/
public static String sendPost(String httpUrl, String content) {
StringBuffer sb = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
try {
// 创建url 资源
URL url = new URL(httpUrl);
// 创建http 连接
conn = (HttpURLConnection) url.openConnection();
// 设置允许输出
conn.setDoOutput(true);
// 设置允许输入
conn.setDoInput(true);
// 设置不使用缓存
conn.setUseCaches(false);
// 设置传递方式
conn.setRequestMethod("POST");
// 设置维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
// 设置文件字符集:
conn.setRequestProperty("Charset", "UTF-8");
// 转换为字节数组
byte[] data = content.getBytes("UTF-8");
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
// 开始连接请求
conn.connect();
// 创建写入流,写入请求的字符串
out = new DataOutputStream(conn.getOutputStream());
out.write(data);
// 请求返回的状态
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
// 请求返回的数据,解压缩
InputStream is = conn.getInputStream();
GZIPInputStream gzis = new GZIPInputStream(is);
InputStreamReader reader = new InputStreamReader(gzis, "UTF-8");
BufferedReader br = new BufferedReader(reader);
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
System.out.println("第三方返回的zip解压缩之后的报文:" + sb);
return sb.toString();
} else {
System.out.println("请求失败!!!");
}
} catch (
IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
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