-
搭建SpringBoot框架
-
pom.xml 引入依賴
<!-- 微信httpclient 獲取用戶 openId-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.21</version>
</dependency>
<!-- log4j日誌 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
3.引入發送微信請求工具類
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
public class HttpClientUtils
{
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日誌記錄
private static RequestConfig requestConfig = null;
static
{
// 設置請求和傳輸超時時
requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
}
/**
* post請求傳輸json參數
* @param url url地址
* @param json 參數
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam)
{
// post請求返回結果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 設置請求和傳輸超時時請求
httpPost.setConfig(requestConfig);
try
{
System.out.println(jsonParam);
if (null != jsonParam)
{
// 解決中文亂碼問題
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
System.out.println(jsonParam);
CloseableHttpResponse result = httpClient.execute(httpPost);
// 請求發請求成功,並得到響應
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String str = "";
try
{
// 讀取服務器返回過來的json字符串數
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串轉換成json對象
jsonResult = JSONObject.parseObject(str);
}
catch (Exception e)
{
logger.error("post請求提交失敗:" + url, e);
}
}
}
catch (IOException e)
{
logger.error("post請求提交失敗:" + url, e);
}
finally
{
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post請求傳輸String參數 例如:name=Jack&sex=1&type=2
* Content-type:application/x-www-form-urlencoded
* @param url url地址
* @param strParam 參數
* @return
*/
public static JSONObject httpPost(String url, String strParam)
{
// post請求返回結果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
try
{
if (null != strParam)
{
// 解決中文亂碼問題
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 請求發宋成功,並得到響應
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String str = "";
try
{
// 讀取服務器返回過來的json字符串數據
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串轉換成json對象
jsonResult = JSONObject.parseObject(str);
}
catch (Exception e)
{
logger.error("post請求提交失敗:" + url, e);
}
}
}
catch (IOException e)
{
logger.error("post請求提交失敗:" + url, e);
}
finally
{
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* 發�?�get請求
* @param url 路徑
* @return
*/
public static JSONObject httpGet(String url)
{
// get請求返回結果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 發�?�get請求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try
{
CloseableHttpResponse response = client.execute(request);
// 請求發�?�成功,並得到響�?
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 讀取服務器返回過來的json字符串數�?
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串轉換成json對象
jsonResult = JSONObject.parseObject(strResult);
}
else
{
logger.error("get請求提交失敗:" + url);
}
}
catch (IOException e)
{
logger.error("get請求提交失敗:" + url, e);
}
finally
{
request.releaseConnection();
}
return jsonResult;
}
}
4.調用方法 測試
public static void main(String[] args) {
//url中的 appid 和 secret 開發者會給你 這相當於你小程序的ID和密碼 js_code 也會給你 js_code是用微信開發者工具調用方法獲得
String appid="";//你小程序Id
String secret="";//填入你小程序的secret
String code="";//用微信開發者工具獲取到的code
String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
JSONObject jsonObj=HttpClientUtils.httpGet(url);
System.out.println(jsonObj);
//打印結果
}
**如有缺少 請留言**