本文整理汇总了Java中javax.net.ssl.HttpsURLConnection.getOutputStream方法的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection.getOutputStream方法的具体用法?Java HttpsURLConnection.getOutputStream怎么用?Java HttpsURLConnection.getOutputStream使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.HttpsURLConnection
的用法示例。
在下文中一共展示了HttpsURLConnection.getOutputStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Pings the server
*
* @source https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
* */
private void execute() throws Throwable {
//don't execute on debug-mode
if(this.debugging == true)
return;
String url = "https://redunda.sobotics.org/status.json";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", UserAgent.getUserAgent());
String parameters = "key="+this.apiKey;
//add version parameter if available
if (this.version != null)
parameters = parameters+"&version="+this.version;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString();
//http://stackoverflow.com/a/15116323/4687348
JsonParser jsonParser = new JsonParser();
JsonObject object = (JsonObject)jsonParser.parse(responseString);
try {
boolean standbyResponse = object.get("should_standby").getAsBoolean();
boolean oldValue = PingService.standby.get();
PingService.standby.set(standbyResponse);
String newLocation = object.get("location").getAsString();
PingService.location = newLocation;
if (standbyResponse != oldValue) {
if (this.delegate != null)this.delegate.standbyStatusChanged(standbyResponse);
}
} catch (Throwable e) {
//no apikey or server might be offline; don't change status!
this.forwardError(e);
throw e;
}
}
示例2: reSend
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 重发
*
* @param urlStr
* @param parameters
* @param count
*/
private static void reSend(String urlStr, String parameters, Map<String, Integer> count) throws IOException {
if (count.get("times") == null) {
count.put("times", 0);
}
int times = count.get("times");
if (times < 5) {
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
OutputStream output = conn.getOutputStream();
output.write(parameters.getBytes("utf-8"));
output.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String s = null;
StringBuilder sb = new StringBuilder();
while ((s = reader.readLine()) != null) {
sb.append(s);
}
reader.close();
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
String errcode = jsonObject.get("errcode").toString();
if (!errcode.equals("0")) {
count.put("times", count.get("times") + 1);
reSend(urlStr, parameters, count);
}
}
}
示例3: sendData
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
示例4: sendData
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
示例5: sendData
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
final byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
outputStream.flush();
}
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
示例6: fetchToken
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
String fetchToken() {
try {
URL obj = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic ZlR1SWpXV1RUZkpHSlNaajBHdDZKTXQ3cXc0YTptTHhoNWpCVWdsTldWb3NqeXpjZjhTYjBKNGNh");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("grant_type=client_credentials&scope=device_123");
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
示例7: begin
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
void begin() throws IOException {
try {
_conn = (HttpsURLConnection) _url.openConnection();
_conn.setRequestMethod("POST");
for (Map.Entry<String, String> entry : _config.header.entrySet()) {
_conn.setRequestProperty(entry.getKey(), entry.getValue());
}
_conn.setUseCaches(false);
_conn.setDoInput(false);
_conn.setDoOutput(true);
_conn.connect();
_writer = new BufferedWriter(new OutputStreamWriter(_conn.getOutputStream()));
_writer.append("{\"app\":\"").append(_config.app)
.append("\",\"version\":\"").append(_config.version)
.append("\",\"relay_app_id\":\"").append(_config.relayAppId);
if (_envInfo.device != null) {
_writer.append("\",\"device\":\"").append(_envInfo.device);
}
if (_envInfo.getAppUsedMemory() > 0) {
_writer.append("\",\"app_mem_used\":\"").append(Long.toString(_envInfo.getAppUsedMemory()));
}
if (_envInfo.getDeviceFreeMemory() > 0) {
_writer.append("\",\"device_mem_free\":\"").append(Long.toString(_envInfo.getDeviceFreeMemory()));
}
if (_envInfo.getDeviceTotalMemory() > 0) {
_writer.append("\",\"device_mem_total\":\"").append(Long.toString(_envInfo.getDeviceTotalMemory()));
}
if (_envInfo.getBatteryLevel() > 0) {
_writer.append("\",\"battery_level\":\"").append(Float.toString(_envInfo.getBatteryLevel()));
}
if (_envInfo.getCountry() != null) {
_writer.append("\",\"country\":\"").append(_envInfo.getCountry());
}
if (_envInfo.getRegion() != null) {
_writer.append("\",\"region\":\"").append(_envInfo.getRegion());
}
if (_envInfo.network != null) {
_writer.append("\",\"network\":\"").append(_envInfo.network);
}
if (_envInfo.osName != null) {
_writer.append("\",\"os\":\"").append(_envInfo.osName);
}
if (_envInfo.osVersion != null) {
_writer.append("\",\"os_version\":\"").append(_envInfo.osVersion);
}
_writer.append("\",\"measurements\":[");
_measurements = 0;
} catch (Exception e) {
if (_config.debug) {
Log.d(TAG, e.getMessage());
}
disconnect();
if (e instanceof IOException) {
throw e;
}
}
}
示例8: call
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Calls the API
*
* @param cmd
* @return the answer from the
*/
public JsonObject call(String cmd)
{
// Copy the current map to
Map<String, String> req = new HashMap<>();
req.putAll(params);
params.clear();
// Set the API command and required fields
req.put("version", "1");
req.put("cmd", cmd);
req.put("key", this.public_key);
req.put("format", "json");
try {
// Generate the query string
String post_data = urlEncodeUTF8(req);
// Calculate the HMAC
String hmac = HmacUtils.hmacSha512Hex(this.private_key, post_data);
URL obj = new URL("https://www.coinpayments.net/api.php");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// Set the request headers
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("HMAC", hmac);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(post_data);
wr.flush();
wr.close();
// Wait for the resüonse code
int responseCode = con.getResponseCode();
logger.debug("Sending 'POST' request to URL : https://www.coinpayments.net/api.php");
logger.debug("Post parameters : " + post_data);
logger.debug("Response Code : " + responseCode);
// Read the full response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Parse the JSON response with GSON
JsonParser jsonParser = new JsonParser();
JsonElement jsonTree = jsonParser.parse(response.toString());
JsonObject jsonObject = jsonTree.getAsJsonObject();
// If there is an error - throw an Exception
if (jsonObject.get("error").getAsString().equals("ok") == false) {
throw new IllegalStateException(jsonObject.get("error").getAsString());
}
// Otherwise return the result object
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String prettyJson = gson.toJson(jsonObject);
logger.debug(prettyJson);
return jsonObject.getAsJsonObject("result");
}
catch (Exception e) {
logger.error("Exception occured: " + e.getMessage());
throw new CoinpaymentsApiCallException(e.getMessage());
}
}
示例9: deleteKfAccount
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 删除客服帐号
*
* @param keFu
* @return
*/
public static boolean deleteKfAccount(KeFu keFu) {
boolean isOk = false;
String token = WeiXinUtils.getToken();
if (token != null) {
String urlString = "https://api.weixin.qq.com/customservice/kfaccount/del?access_token=" + token;
try {
URL url = new URL(urlString);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
String kfAccountString = JSONObject.toJSONString(keFu);
httpsURLConnection.setRequestProperty("Content-length", String.valueOf(kfAccountString.length()));
httpsURLConnection.setRequestProperty("Content-Type", "application/json");
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
dataOutputStream.write(kfAccountString.getBytes());
dataOutputStream.flush();
dataOutputStream.close();
DataInputStream dataInputStream = new DataInputStream(httpsURLConnection.getInputStream());
StringBuffer stringBuffer = new StringBuffer();
int inputByte = dataInputStream.read();
while (inputByte != -1) {
stringBuffer.append((char) inputByte);
inputByte = dataInputStream.read();
}
String kfString = stringBuffer.toString();
JSONObject jsonObject = JSON.parseObject(kfString);
if (jsonObject.containsKey("errcode")) {
int errcode = jsonObject.getIntValue("errcode");
if (errcode == 0) {
isOk = true;
} else {
//TODO 添加客服账号失败
isOk = false;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return isOk;
}
示例10: updateKfAccount
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 修改客服帐号
*
* @param keFu
* @return
*/
public static boolean updateKfAccount(KeFu keFu) {
boolean isOk = false;
String token = WeiXinUtils.getToken();
if (token != null) {
String urlString = "https://api.weixin.qq.com/customservice/kfaccount/update?access_token=" + token;
try {
URL url = new URL(urlString);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
String kfAccountString = JSONObject.toJSONString(keFu);
httpsURLConnection.setRequestProperty("Content-length", String.valueOf(kfAccountString.length()));
httpsURLConnection.setRequestProperty("Content-Type", "application/json");
httpsURLConnection.setDoOutput(true);
httpsURLConnection.setDoInput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpsURLConnection.getOutputStream());
dataOutputStream.write(kfAccountString.getBytes());
dataOutputStream.flush();
dataOutputStream.close();
DataInputStream dataInputStream = new DataInputStream(httpsURLConnection.getInputStream());
StringBuffer stringBuffer = new StringBuffer();
int inputByte = dataInputStream.read();
while (inputByte != -1) {
stringBuffer.append((char) inputByte);
inputByte = dataInputStream.read();
}
String kfString = stringBuffer.toString();
JSONObject jsonObject = JSON.parseObject(kfString);
if (jsonObject.containsKey("errcode")) {
int errcode = jsonObject.getIntValue("errcode");
if (errcode == 0) {
isOk = true;
} else {
//TODO 添加客服账号失败
isOk = false;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return isOk;
}
示例11: upload
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static String upload(File file) throws IOException {
String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + WeiXinCompanyUtils.getToken()
+ "&type=file";
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
URL uploadUrl = new URL(urlStr);
HttpsURLConnection uploadConn = (HttpsURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
// 从请求头中获取内容类型
String contentType = "text";
// 根据内容类型判断文件扩展名
String ext = file.getName().substring(file.getName().lastIndexOf("."));
String name = file.getName();
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
String aaa = String
.format("Content-Disposition: form-data; name=\"media\"; filename=\"" + name + "." + "%s\"\r\n", ext);
outputStream.write(aaa.getBytes());
String bbb = String.format("Content-Type: %s\r\n\r\n", contentType);
outputStream.write(bbb.getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
uploadConn.disconnect();
System.out.println(buffer.toString());
return buffer.toString();
}
示例12: upload
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static String upload(String fileName, File file) throws IOException {
String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + WeiXinCompanyUtils.getToken()
+ "&type=file";
// 定义数据分隔符
String boundary = "------------7da2e536604c8";
URL uploadUrl = new URL(urlStr);
HttpsURLConnection uploadConn = (HttpsURLConnection) uploadUrl.openConnection();
uploadConn.setDoOutput(true);
uploadConn.setDoInput(true);
uploadConn.setRequestMethod("POST");
// 设置请求头Content-Type
uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 获取媒体文件上传的输出流(往微信服务器写数据)
OutputStream outputStream = uploadConn.getOutputStream();
// 从请求头中获取内容类型
String contentType = "text";
// 根据内容类型判断文件扩展名
@SuppressWarnings("unused")
String[] f = fileName.split("\\.");
// 请求体开始
outputStream.write(("--" + boundary + "\r\n").getBytes());
// String aaa = String.format("Content-Disposition: form-data;
// name=\"media\"; filename=\""+f[0]+"."+"%s\"\r\n", f[1]);
String aaa = "Content-Disposition: form-data; name=\"media\"; filename=\"" + fileName + "\"\r\n";
outputStream.write(aaa.getBytes());
String bbb = String.format("Content-Type: %s\r\n\r\n", contentType);
outputStream.write(bbb.getBytes());
// 获取媒体文件的输入流(读取文件)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流(往微信服务器写数据)
outputStream.write(buf, 0, size);
}
// 请求体结束
outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
outputStream.close();
bis.close();
// 获取媒体文件上传的输入流(从微信服务器读数据)
InputStream inputStream = uploadConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
uploadConn.disconnect();
System.out.println(buffer.toString());
return buffer.toString();
}
示例13: verify
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public static boolean verify(String gRecaptchaResponse){
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try{
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject object = (JSONObject)JSONValue.parse(new StringReader(response.toString()));
return (Boolean)object.get("success");
}catch(Exception e){
e.printStackTrace();
return false;
}
}
示例14: httpsRequest
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 发起https请求并获取结果
*
* @param requestUrl
* 请求地址
* @param requestMethod
* 请求方式(GET、POST)
* @param outputStr
* 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new SaicX509TrustManager() };
// SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
logger.error("connection timed out cause by " + ce.getMessage());
} catch (Exception e) {
logger.error("https request error : " + e.getMessage());
}
return jsonObject;
}
示例15: sendFileMsg
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 发送多媒体文件
*
* @return
*/
public static String sendFileMsg(String touser, String toparty, String totag, int agentid, String media_id,
boolean safe) throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("touser", touser);// 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
jsonObject.put("toparty", toparty);// 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
jsonObject.put("totag", totag);// 标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数
jsonObject.put("agentid", agentid + "");// 企业应用的id,整型。可在应用的设置页面查看
jsonObject.put("msgtype", "file");// 消息类型,此时固定为:text
JSONObject text = new JSONObject();
text.put("media_id", media_id);
jsonObject.put("file", text);// 消息内容
if (safe) {
jsonObject.put("safe", "1");// 表示是否是保密消息,0表示否,1表示是,默认0
} else {
jsonObject.put("safe", "0");// 表示是否是保密消息,0表示否,1表示是,默认0
}
System.out.println(jsonObject);
String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
+ WeiXinCompanyUtils.getToken();
String parameters = jsonObject.toString();
URL url = new URL(urlStr);
System.out.println("url:" + urlStr);
System.out.println("parameters:" + parameters);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream output = conn.getOutputStream();
output.write(parameters.getBytes("utf-8"));
output.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String s = null;
StringBuilder sb = new StringBuilder();
while ((s = reader.readLine()) != null) {
sb.append(s);
}
reader.close();
System.out.println(sb.toString());
return sb.toString();
}