package com.sandu.ximon.admin.utils;
|
|
import org.apache.http.HttpResponse;
|
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.message.BasicHeader;
|
import org.apache.http.protocol.HTTP;
|
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.util.ArrayList;
|
import java.util.List;
|
|
/**
|
* 音柱用POST工具类
|
*/
|
public class BroadcastPostUtils {
|
|
|
public static String Post(String json, String URL, String charset) {
|
CloseableHttpClient client = HttpClients.createDefault();
|
HttpPost post = new HttpPost(URL);
|
post.setHeader("Content-Type", "application/json");
|
String result = null;
|
try {
|
StringEntity s = new StringEntity(json, charset);
|
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
|
"application/json"));
|
post.setEntity(s);
|
HttpResponse httpResponse = client.execute(post);
|
InputStream inStream = httpResponse.getEntity().getContent();
|
|
result = streamToString(inStream, charset);
|
|
inStream.close();
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
}
|
return result;
|
}
|
|
/**
|
* m 1 1 1
|
* f 1 1 1
|
* y 1
|
* @param in
|
* @param encoding
|
* @return
|
*/
|
|
public static String streamToString(InputStream in, String encoding) {
|
// 将流转换为字符串
|
try {
|
StringBuffer sb = new StringBuffer();
|
byte[] b = new byte[1024];
|
for (int n; (n = in.read(b)) != -1; ) {
|
sb.append(new String(b, 0, n, encoding));
|
}
|
return sb.toString();
|
} catch (IOException e) {
|
e.printStackTrace();
|
throw new RuntimeException("提取 requestBody 异常", e);
|
}
|
}
|
|
|
public static String taskPostEncoding(String json, String URL) {
|
CloseableHttpClient client = HttpClients.createDefault();
|
HttpPost post = new HttpPost(URL);
|
post.setHeader("Content-Type", "application/json");
|
post.addHeader("Authorization", "Basic YWRtaW46");
|
String result = null;
|
List<String> list = new ArrayList<>();
|
try {
|
StringEntity s = new StringEntity(json, "utf-8");
|
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
|
"application/json"));
|
post.setEntity(s);
|
HttpResponse httpResponse = client.execute(post);
|
InputStream inStream = httpResponse.getEntity().getContent();
|
|
result = streamToString(inStream, "utf-8");
|
|
|
inStream.close();
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
}
|
return result;
|
}
|
|
|
}
|