根據圖片的描述是通過發送https請求上傳圖片。微信公眾號提供的文檔是通過curl命令來實現發送https post請求,但是我現在的程序是通過java程序來發送https post請求。以下是我的3個問題:
1、既然是發送https post請求上傳圖片,java應該也可以實現,我只實現過java https post的簡單請求,沒有實現過java https post圖片上傳。有大神能幫幫我嗎?
2、既然微信公眾號文檔上說是通過curl來發送請求,那java是否提供模擬curl來發送https post請求來實現圖片上傳。如果java提供,有大神能幫幫我嗎?
3、或者有沒有誰實現過微信公眾號以上截圖描述的用java實現的多媒體文件上傳功能,有實現過的話,共享以下代碼啊!本人感激不盡!。
求大神幫幫忙!
這個類,剛忘了一個方法httpsRequestToString,補充如下:
/**
* 發送請求以https方式發送請求並將請求響應內容以String方式返回
* @param path 請求路徑
* @param method 請求方法
* @param body 請求數據體
* @return 請求響應內容轉換成字符串信息
*/
public static String httpsRequestToString(String path, String method, String body) {
if(path==null||method==null){
return null;
}
String response = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
HttpsURLConnection conn = null;
try {
TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
System.out.println(path);
URL url = new URL(path);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);
if (null != body) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(body.getBytes("UTF-8"));
outputStream.close();
}
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
response = buffer.toString();
} catch (Exception e) {
logger.error(e);
}finally{
if(conn!=null){
conn.disconnect();
}
try {
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
} catch (IOException execption) {
logger.error(execption);
}
}
return response;
}
此外,還有一個證書實現類,發送https請求用的,也要定義的。
class JEEWeiXinX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}