这个是之前做的一个小demo,因为条件所致,没法使用mybatis。于是当时自己手动写了一段简单的 jdbd连接数据库,从couple表中,将叫做”cp_img”的一列遍历(这一列的数据都是存储在服务器上的图片),并打印在本地的文件夹中。话不多说,直接上代码。
import com.alibaba.fastjson.JSON;
import com.sf.lottery.common.utils.StrUtils;
import com.sf.lottery.web.weixin.domain.AccessTokenReturn;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.*;
public class saveCoupleImg {
public static void main(String[] args) throws IOException {
private String appId="xxxxxxx";
private String appSecret = "xxxxxxxxx";
try {
//1、加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//2、建立连接 建立连接很耗时间 因为连接内部其实包含了Socket对象,是一个远程的连接。比较耗时。
Connection conn = DriverManager.getConnection(
"jdbc:mysql://xxxxx:xxxxx/lottery?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true",
"xxx", "xxxxxx");
PreparedStatement query=
conn.prepareStatement("select * from couple");
ResultSet rs = query.executeQuery();
HttpRequest httpRequest = new HttpRequest();
String s = httpRequest .sendGet("http://xxxxxx.xxxx/weixin/accessToken","");
File file =new File("D:\\cp");
//如果文件夹不存在则创建
if (!file .exists() && !file .isDirectory())
{
file .mkdir();
}
while(rs.next()){
int user1_sf_num = rs.getInt("user1_sf_num");
int user2_sf_num = rs.getInt("user2_sf_num");
String imgName = "D:\\cp\\"+user1_sf_num+"&"+user2_sf_num + ".jpg";
//数据库中存储的仅仅是rs.getString("cp_img"),要和token拼到一起,然后去微信的服务器上把图片下载下来
String cp_img = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + s + "&media_id=" + rs.getString("cp_img");
//String cp_img = rs.getString("cp_img");
printImg(imgName,cp_img);
}
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printImg(String imgName, String imgSrc) {
URL url = null;
try {
url = new URL(imgSrc);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(imgName));
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
}
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面是获取微信token的类,这是因为微信的token是变化的
package com.sf.lottery.web.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
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.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@Component
public class HttpRequest {
@Value("${http.isProxy}")
private boolean isProxy;
@Value("${http.proxyHost}")
private String proxyHost;
@Value("${http.proxyPort}")
private int proxyPort;
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果content的json串,例如 *httpRequest.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token",
"appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code");
*/
public String sendGet(String url, String param) throws Exception {
HttpGet httpget = new HttpGet(new StringBuilder().append(url).append("?").append(param).toString());
//配置请求的超时设置
RequestConfig requestConfig = null;
CloseableHttpClient httpclient = buildSSLCloseableHttpClient();
httpget.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(entity,"utf-8");
return jsonStr;
} finally {
httpget.releaseConnection();
}
}
private CloseableHttpClient buildSSLCloseableHttpClient() throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
if (isProxy) {
HttpRoutePlanner routePlanner = new HttpRoutePlanner() {
@Override
public HttpRoute determineRoute(HttpHost httpHost, org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws HttpException {
return new HttpRoute(httpHost, null, new HttpHost(proxyHost, proxyPort),
"https".equalsIgnoreCase(httpHost.getSchemeName()));
}
};
return HttpClients.custom()
.setRoutePlanner(routePlanner).setSSLSocketFactory(sslsf)
.build();
} else {
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
}
}
说明:
转载请注明出处
http://blog.csdn.net/antony9118/article/details/70989025