集成微信小程序登录和微信公众号登录

This commit is contained in:
D 2024-01-16 02:09:33 +08:00
parent 7b4b354e95
commit f468d57607
13 changed files with 671 additions and 32 deletions

76
doc/微信登录.drawio Normal file
View File

@ -0,0 +1,76 @@
<mxfile host="65bd71144e">
<diagram id="X-9zxwZzwVme25TE_fPk" name="第 1 页">
<mxGraphModel dx="1002" dy="1732" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" value="微信小程序" style="shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;" vertex="1" parent="1">
<mxGeometry x="100" y="130" width="100" height="390" as="geometry"/>
</mxCell>
<mxCell id="16" value="" style="html=1;points=[];perimeter=orthogonalPerimeter;" vertex="1" parent="2">
<mxGeometry x="45" y="140" width="10" height="40" as="geometry"/>
</mxCell>
<mxCell id="17" value="wx.login" style="edgeStyle=orthogonalEdgeStyle;html=1;align=left;spacingLeft=2;endArrow=block;rounded=0;entryX=1;entryY=0;" edge="1" target="16" parent="2">
<mxGeometry relative="1" as="geometry">
<mxPoint x="50" y="120" as="sourcePoint"/>
<Array as="points">
<mxPoint x="80" y="120"/>
</Array>
</mxGeometry>
</mxCell>
<mxCell id="20" value="" style="html=1;points=[];perimeter=orthogonalPerimeter;" vertex="1" parent="2">
<mxGeometry x="45" y="260" width="10" height="40" as="geometry"/>
</mxCell>
<mxCell id="3" value="开发者服务器" style="shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;" vertex="1" parent="1">
<mxGeometry x="330" y="130" width="100" height="390" as="geometry"/>
</mxCell>
<mxCell id="9" value="" style="html=1;points=[];perimeter=orthogonalPerimeter;" vertex="1" parent="3">
<mxGeometry x="45" y="170" width="10" height="110" as="geometry"/>
</mxCell>
<mxCell id="4" value="微信接口服务" style="shape=umlLifeline;perimeter=lifelinePerimeter;whiteSpace=wrap;html=1;container=1;collapsible=0;recursiveResize=0;outlineConnect=0;" vertex="1" parent="1">
<mxGeometry x="590" y="130" width="100" height="400" as="geometry"/>
</mxCell>
<mxCell id="11" value="" style="html=1;points=[];perimeter=orthogonalPerimeter;" vertex="1" parent="4">
<mxGeometry x="45" y="175" width="10" height="60" as="geometry"/>
</mxCell>
<mxCell id="8" value="" style="html=1;verticalAlign=bottom;endArrow=block;exitX=0.9;exitY=0.89;exitDx=0;exitDy=0;exitPerimeter=0;" edge="1" parent="1" source="16" target="9">
<mxGeometry width="80" relative="1" as="geometry">
<mxPoint x="155" y="305" as="sourcePoint"/>
<mxPoint x="290" y="340" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="12" value="携带code" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];" vertex="1" connectable="0" parent="8">
<mxGeometry x="-0.1218" y="-1" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="10" value="携带appid、appsecret、code" style="html=1;verticalAlign=bottom;endArrow=block;entryX=-0.02;entryY=0.01;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="9" target="11">
<mxGeometry width="80" relative="1" as="geometry">
<mxPoint x="460" y="330" as="sourcePoint"/>
<mxPoint x="550" y="330" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="18" value="返回session_key、openid" style="html=1;verticalAlign=bottom;endArrow=open;dashed=1;endSize=8;entryX=1.02;entryY=0.567;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="11" target="9">
<mxGeometry relative="1" as="geometry">
<mxPoint x="574" y="360" as="sourcePoint"/>
<mxPoint x="414" y="360" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="19" value="返回token" style="html=1;verticalAlign=bottom;endArrow=open;dashed=1;endSize=8;entryX=0.98;entryY=0.235;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="9" target="20">
<mxGeometry relative="1" as="geometry">
<mxPoint x="290" y="400" as="sourcePoint"/>
<mxPoint x="210" y="400" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="21" value="code临时登录凭证只能使用一次&lt;br&gt;appid开发者id&lt;br&gt;appsecret开发者密码&lt;br&gt;openid用户唯一标识&lt;br&gt;session_key会话密钥对用户数据进行加密的签名" style="html=1;dropTarget=0;align=left;" vertex="1" parent="1">
<mxGeometry x="90" y="-80" width="300" height="160" as="geometry"/>
</mxCell>
<mxCell id="22" value="" style="shape=module;jettyWidth=8;jettyHeight=4;" vertex="1" parent="21">
<mxGeometry x="1" width="20" height="20" relative="1" as="geometry">
<mxPoint x="-27" y="7" as="offset"/>
</mxGeometry>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

24
pom.xml
View File

@ -73,6 +73,7 @@
<version>${mybatis-plus-boot-starter.version}</version> <version>${mybatis-plus-boot-starter.version}</version>
</dependency> </dependency>
<!-- javax -->
<dependency> <dependency>
<groupId>javax.xml.bind</groupId> <groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId> <artifactId>jaxb-api</artifactId>
@ -115,19 +116,6 @@
<version>${oshi.version}</version> <version>${oshi.version}</version>
</dependency> </dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- io常用工具类 --> <!-- io常用工具类 -->
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
@ -212,6 +200,13 @@
<version>${ruoyi.version}</version> <version>${ruoyi.version}</version>
</dependency> </dependency>
<!-- 集成第三方登录 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-third-auth</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<dependency> <dependency>
<groupId>jakarta.servlet</groupId> <groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId> <artifactId>jakarta.servlet-api</artifactId>
@ -235,6 +230,7 @@
<module>ruoyi-quartz</module> <module>ruoyi-quartz</module>
<module>ruoyi-generator</module> <module>ruoyi-generator</module>
<module>ruoyi-common</module> <module>ruoyi-common</module>
<module>ruoyi-third-auth</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
@ -284,4 +280,4 @@
</pluginRepository> </pluginRepository>
</pluginRepositories> </pluginRepositories>
</project> </project>

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>ruoyi</artifactId> <artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
@ -52,6 +53,12 @@
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId> <artifactId>ruoyi-generator</artifactId>
</dependency> </dependency>
<!-- 集成第三方登录 -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-third-auth</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -81,4 +88,4 @@
<finalName>${project.artifactId}</finalName> <finalName>${project.artifactId}</finalName>
</build> </build>
</project> </project>

View File

@ -0,0 +1,14 @@
# MyBatis Plus配置
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql

View File

@ -0,0 +1,12 @@
# 请输入自己的appid和appsecret
wx:
miniapp:
open: true
appId: miniAppid
appSecret: miniAppSercret
url: https://api.weixin.qq.com/sns/jscode2session
h5:
open: true
appId: h5AppId
appSecret: h5Secret
url: https://api.weixin.qq.com/sns/oauth2/access_token

View File

@ -55,7 +55,7 @@ spring:
# 国际化资源文件路径 # 国际化资源文件路径
basename: i18n/messages basename: i18n/messages
profiles: profiles:
active: druid active: druid,mybatis,thirdAuth
# 文件上传 # 文件上传
servlet: servlet:
multipart: multipart:
@ -101,21 +101,6 @@ token:
# 令牌有效期默认30分钟 # 令牌有效期默认30分钟
expireTime: 30 expireTime: 30
# MyBatis Plus配置
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
# Swagger配置 # Swagger配置
swagger: swagger:
# 是否开启swagger # 是否开启swagger

35
ruoyi-third-auth/pom.xml Normal file
View File

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.8.7.3.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-third-auth</artifactId>
<description>
system系统模块
</description>
<dependencies>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,52 @@
package com.ruoyi.third.constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WxH5Constant {
@Value("${wx.h5.appId}")
private String appId;
@Value("${wx.h5.appSecret}")
private String appSecret;
@Value("${wx.h5.url}")
private String url;
@Value("${wx.h5.open}")
private Boolean open;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
}

View File

@ -0,0 +1,52 @@
package com.ruoyi.third.constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WxMiniAppConstant {
@Value("${wx.miniapp.appId}")
private String appId;
@Value("${wx.miniapp.appSecret}")
private String appSecret;
@Value("${wx.miniapp.url}")
private String url;
@Value("${wx.miniapp.open}")
private Boolean open;
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
}

View File

@ -0,0 +1,40 @@
package com.ruoyi.third.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.third.constant.WxH5Constant;
import com.ruoyi.third.constant.WxMiniAppConstant;
import com.ruoyi.third.service.Impl.WxLoginServiceImpl;;
@RestController
@RequestMapping("/wx")
public class WxLoginService extends BaseController {
@Autowired
public WxH5Constant wxH5AppConstant;
@Autowired
public WxMiniAppConstant wxMiniAppConstant;
@Autowired
WxLoginServiceImpl wxLoginServiceImpl;
@Anonymous
@GetMapping("/miniapp/{code}")
public AjaxResult loginMiniApp(@PathVariable("code") String code) {
return success(wxLoginServiceImpl.doLoginMiniApp(code));
}
@Anonymous
@GetMapping("/h5/{code}")
public AjaxResult loginH5App(@PathVariable("code") String code) {
return success(wxLoginServiceImpl.doLoginMiniApp(code));
}
}

View File

@ -0,0 +1,65 @@
package com.ruoyi.third.service.Impl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.third.constant.WxH5Constant;
import com.ruoyi.third.constant.WxMiniAppConstant;
import com.ruoyi.third.service.WxLoginService;
import com.ruoyi.third.utils.HttpClientUtil;
@Service
public class WxLoginServiceImpl implements WxLoginService {
@Autowired
private WxMiniAppConstant wxAppConstant;
@Autowired
private WxH5Constant wxH5Constant;
@Autowired
private HttpClientUtil httpClientUtil;
public Map<String, String> doLogin(String url, String appid, String secret, String code) {
String getMessageUrl = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + code
+ "&grant_type=authorization_code";
String result = httpClientUtil.sendHttpGet(getMessageUrl);
JSONObject jsonObject = JSON.parseObject(result);
if (jsonObject.containsKey("openid")) {
String openid = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
return new HashMap<String, String>() {
{
put("openid", openid);
put("sessionKey", sessionKey);
}
};
} else {
throw new ServiceException(jsonObject.getString("errmsg"), jsonObject.getIntValue("errcode"));
}
}
@Override
public String doLoginH5(String code) {
return doLogin(
wxH5Constant.getUrl(),
wxH5Constant.getAppId(),
wxH5Constant.getAppSecret(),
code).get("openid");
}
@Override
public String doLoginMiniApp(String code) {
return doLogin(
wxAppConstant.getUrl(),
wxAppConstant.getAppId(),
wxAppConstant.getAppSecret(),
code).get("openid");
}
}

View File

@ -0,0 +1,7 @@
package com.ruoyi.third.service;
public interface WxLoginService {
public String doLoginMiniApp(String code);
public String doLoginH5(String code);
}

View File

@ -0,0 +1,298 @@
package com.ruoyi.third.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
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 org.springframework.stereotype.Component;
@Component
public class HttpClientUtil {
/**
* 默认参数设置
* setConnectTimeout设置连接超时时间单位毫秒
* setConnectionRequestTimeout设置从connect Manager获取Connection 超时时间单位毫秒
* setSocketTimeout请求获取数据的超时时间单位毫秒访问一个接口多少时间内无法返回数据就直接放弃此次调用 暂时定义15分钟
*/
private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
/**
* 静态内部类---作用单例产生类的实例
*
* @author Administrator
*/
private static class LazyHolder {
private static final HttpClientUtil INSTANCE = new HttpClientUtil();
}
private HttpClientUtil() {
}
public static HttpClientUtil getInstance() {
return LazyHolder.INSTANCE;
}
/**
* 发送 post请求
*
* @param httpUrl 地址
*/
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
return sendHttpPost(httpPost);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
*/
public String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
//设置参数
StringEntity stringEntity = new StringEntity(params, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送 post请求
*
* @param httpUrl 地址
* @param maps 参数
*/
public String sendHttpPost(String httpUrl, Map<String, String> maps) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
// 创建参数队列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送Post请求
*
* @param httpPost
* @return
*/
private String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
// 执行请求
long execStart = System.currentTimeMillis();
response = httpClient.execute(httpPost);
long execEnd = System.currentTimeMillis();
System.out.println("=================执行post请求耗时" + (execEnd - execStart) + "ms");
long getStart = System.currentTimeMillis();
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
long getEnd = System.currentTimeMillis();
System.out.println("=================获取响应结果耗时:" + (getEnd - getStart) + "ms");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送 get请求
*
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpGet(httpGet);
}
/**
* 发送 get请求Https
*
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
return sendHttpsGet(httpGet);
}
/**
* 发送Get请求
*
* @param httpGet
* @return
*/
private String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送Get请求Https
*
* @param httpGet
* @return
*/
private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
/**
* 发送xml数据
*
* @param url
* @param xmlData
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static HttpResponse sendXMLDataByPost(String url, String xmlData)
throws ClientProtocolException, IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity entity = new StringEntity(xmlData);
httppost.setEntity(entity);
httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
HttpResponse response = httpClient.execute(httppost);
return response;
}
/**
* 获得响应HTTP实体内容
*
* @param response
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
public static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = br.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
sb.append(line + "\n");
line = br.readLine();
}
return sb.toString();
}
return "";
}
}