package com.zc.business.controller; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * @author 王思祥 * @ClassName DcWarningPush 微博推送 */ public class WeiboAuthUtil { private static final String ACCESS_TOKEN = "2.00oesadIn1MNEC0296dd00f87jmhaC"; private static final String WEIBO_API_URL = "https://api.weibo.com/2/statuses/update.json"; public static void main(String[] args) { try { String text = "这是一条通过Java和微博API推送的消息!"; // 你要推送的微博内容 postWeibo(text); } catch (Exception e) { e.printStackTrace(); } } private static void postWeibo(String status) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(WEIBO_API_URL); // 设置请求头,包含Content-Type httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); httpPost.setHeader("Authorization", "Bearer " + ACCESS_TOKEN); // 构造POST请求参数列表 List params = new ArrayList<>(); params.add(new BasicNameValuePair("access_token", ACCESS_TOKEN)); params.add(new BasicNameValuePair("status", status)); // 将参数列表转换为URL编码的字符串 StringEntity paramsEntity = new StringEntity(EntityUtils.toString(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8)), StandardCharsets.UTF_8); // 设置请求体内容 httpPost.setEntity(paramsEntity); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { String responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8); System.out.println("Response: " + responseString); } // 关闭HttpClient连接 httpClient.close(); } }