官方文档:获取二维码
这里使用其中的接口B:适用于需要的码数量极多的业务场景(无限次数)
参数按照接口说明来传,请求成功的话接口会返回输入流,这里将输入流上传至阿里云OSS,以下是部分JAVA代码(有问题可以留言):
public class UploadTest {
@Test
public void upload(){
try {
URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=你的access_token");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
JSONObject paramJson = new JSONObject();
paramJson.put("scene", "p=1234567890");
paramJson.put("page", "pages/index/index");
paramJson.put("width", 430);
paramJson.put("auto_color", true);
/**
* line_color生效
* paramJson.put("auto_color", false);
* JSONObject lineColor = new JSONObject();
* lineColor.put("r", 0);
* lineColor.put("g", 0);
* lineColor.put("b", 0);
* paramJson.put("line_color", lineColor);
* */printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
//注意 这里上传时文件大小用 HttpResponse.getEntity().getContentLength()
//用 is.available()生成图片会不全,具体参考InputStream.available
AliyunOSSClientUtil.uploadAcode2OSS(httpURLConnection.getInputStream(),"app/demo.png", httpURLConnection.getContentLengthLong()) ;
} catch (Exception e) {
e.printStackTrace();
}
}
}
阿里云oss工具类
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;/**
*
* @ClassName: AliyunOSSClientUtil
* @Description: 阿里云OSS上传文件模块
* @author 张日天
* @date 2018年7月02日 下午23:01:46
*
*/
public class AliyunOSSClientUtil {private static Logger logger = LoggerFactory
.getLogger(AliyunOSSClientUtil.class);
// 阿里云API的内或外网域名
private static String ENDPOINT;
// 阿里云API的密钥Access Key ID
private static String ACCESS_KEY_ID;
// 阿里云API的密钥Access Key Secret
private static String ACCESS_KEY_SECRET;
// 阿里云API的bucket名称
private static String BACKET_NAME;//
private static String FORMATS = OSSClientConstants.FORMATS;
static {
ENDPOINT = SysPropUtils.getPropValue("aliyun.endPoint",
"properties/aliyun.properties");
ACCESS_KEY_ID = SysPropUtils.getPropValue("aliyun.accessKeyId",
"properties/aliyun.properties");
ACCESS_KEY_SECRET = SysPropUtils.getPropValue("ali