package api; import com.alibaba.fastjson.JSON; 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.Map; public class PostUtils { public static String token; public static Map post (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; 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 JSON.parseObject(result,Map.class); } public static Map postWithToken (String json, String URL) { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(URL); post.setHeader("Content-Type", "application/json"); post.addHeader("Authorization", "Basic YWRtaW46"); post.setHeader("token", token); String result = null; 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 JSON.parseObject(result,Map.class); } 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); } } }