当前位置: 首页>>代码示例>>Java>>正文


Java HttpsURLConnection.setRequestProperty方法代码示例

本文整理汇总了Java中javax.net.ssl.HttpsURLConnection.setRequestProperty方法的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection.setRequestProperty方法的具体用法?Java HttpsURLConnection.setRequestProperty怎么用?Java HttpsURLConnection.setRequestProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.net.ssl.HttpsURLConnection的用法示例。


在下文中一共展示了HttpsURLConnection.setRequestProperty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: 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 {
    Validate.notNull(data, "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 :)
}
 
开发者ID:codeHusky,项目名称:HuskyUI-Plugin,代码行数:32,代码来源:Metrics.java

示例2: 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;
	}
}
 
开发者ID:SOBotics,项目名称:Redunda-lib-java,代码行数:65,代码来源:PingService.java

示例3: prepare

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
		 * Prepare.
		 *
		 * @param requestURL the request URL
		 * @return the URL processor
		 * @throws IOException Signals that an I/O exception has occurred.
		 * @throws KeyStoreException 
		 * @throws CertificateException 
		 * @throws NoSuchAlgorithmException 
		 * @throws KeyManagementException 
		 */
		public URLProcessor prepare(URL requestURL) throws IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
//			System.out.println("requestURL=");
//			System.out.println(requestURL);

			connection = (HttpsURLConnection) requestURL.openConnection();
			connection.setInstanceFollowRedirects(false);
			Trust.trustSpecific(connection, truststoreFile);

			connection.setRequestMethod("GET");
			if (accessToken != null) {
				connection.setRequestProperty("Authorization", "Bearer " + accessToken);
			}

			if (uploadFile != null) {
				injectUpload();
			}

			return this;
		}
 
开发者ID:EnFlexIT,项目名称:AgentWorkbench,代码行数:31,代码来源:OIDCAuthorization.java

示例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!");
    }
    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 :)
}
 
开发者ID:Ladinn,项目名称:JavaShell,代码行数:37,代码来源:Metrics.java

示例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!");
	}
	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 :)
}
 
开发者ID:RadBuilder,项目名称:EmojiChat,代码行数:37,代码来源:Metrics.java

示例6: 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;
    }
  }
}
 
开发者ID:rakutentech,项目名称:android-perftracking,代码行数:71,代码来源:EventWriter.java

示例7: get

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
 * 鍙戦�丟et璇锋眰
 * @param url
 * @return
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws IOException 
 * @throws KeyManagementException 
 */
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };  
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
    sslContext.init(null, tm, new java.security.SecureRandom());  
    // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    
    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
    // 杩炴帴瓒呮椂
    http.setConnectTimeout(25000);
    // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
    http.setReadTimeout(25000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setHostnameVerifier(new Verifier());
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null){
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        // 鍏抽棴杩炴帴
        http.disconnect();
    }
    return bufferRes.toString();
}
 
开发者ID:bubicn,项目名称:bubichain-sdk-java,代码行数:46,代码来源:HttpKit.java

示例8: getRawAPIResponse

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String getRawAPIResponse(String urlSuffix, String requestMethod, String body) throws AuthorizationException, IOException, InsufficientValueException, CouldNotFindObjectException {
    URL requestURL = new URL(LightrailConstants.API.apiBaseURL + urlSuffix);
    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) requestURL.openConnection();
    httpsURLConnection.setRequestProperty(
            LightrailConstants.API.AUTHORIZATION_HEADER_NAME,
            LightrailConstants.API.AUTHORIZATION_TOKEN_TYPE + " " + Lightrail.apiKey);
    httpsURLConnection.setRequestMethod(requestMethod);

    if (body != null) {
        httpsURLConnection.setRequestProperty(LightrailConstants.API.CONTENT_TYPE_HEADER_NAME, LightrailConstants.API.CONTENT_TYPE_JSON_UTF8);
        httpsURLConnection.setDoOutput(true);
        OutputStream wr = httpsURLConnection.getOutputStream();
        wr.write(body.getBytes(StandardCharsets.UTF_8));
        wr.flush();
        wr.close();
    }
    int responseCode = httpsURLConnection.getResponseCode();

    InputStream responseInputStream;
    if (httpsURLConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST) {
        responseInputStream = httpsURLConnection.getInputStream();
    } else {
        responseInputStream = httpsURLConnection.getErrorStream();
    }

    BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseInputStream, StandardCharsets.UTF_8));
    StringBuilder responseStringBuffer = new StringBuilder();
    String inputLine;
    while ((inputLine = responseReader.readLine()) != null)
        responseStringBuffer.append(inputLine).append('\n');
    responseReader.close();

    String responseString = responseStringBuffer.toString();

    if (responseCode > 204) {
        handleErrors(responseCode, responseString);
    }

    return responseString;
}
 
开发者ID:Giftbit,项目名称:lightrail-client-java,代码行数:41,代码来源:APICore.java

示例9: 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 :)
}
 
开发者ID:BtoBastian,项目名称:bStats-Metrics,代码行数:35,代码来源:Metrics.java

示例10: post

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
 *  鍙戦�丳ost璇锋眰
 * @param url
 * @param params
 * @return
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄  
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
    // 杩炴帴瓒呮椂
    http.setConnectTimeout(50000);
    // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
    http.setReadTimeout(50000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setHostnameVerifier(new Verifier());
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();

    OutputStream out = http.getOutputStream();
    out.write(params.getBytes("UTF-8"));
    out.flush();
    out.close();

    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null){
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        // 鍏抽棴杩炴帴
        http.disconnect();
    }
    return bufferRes.toString();
}
 
开发者ID:bubicn,项目名称:bubichain-sdk-java,代码行数:52,代码来源:HttpKit.java

示例11: 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;
}
 
开发者ID:youngMen1,项目名称:JAVA-,代码行数:48,代码来源:WeiXinKFUtils.java

示例12: insertKfAccount

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
 * 添加客服帐号
 *
 * @param keFu
 * @return
 */
public static boolean insertKfAccount(KeFu keFu) {
    boolean isOk = false;
    String token = WeiXinUtils.getToken();
    if (token != null) {
        String urlString = "https://api.weixin.qq.com/customservice/kfaccount/add?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;
}
 
开发者ID:youngMen1,项目名称:JAVA-,代码行数:48,代码来源:WeiXinKFUtils.java

示例13: 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();
}
 
开发者ID:guokezheng,项目名称:automat,代码行数:61,代码来源:WeiXinCompanyUpload.java

示例14: getRemoteFileList

import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
 * Returns the list of files on the server as `JsonArray`
 * 
 * @throws Throwable If the download/parsing fails
 * 
 * @return An array of objects with information about the stored files
 * */
public JsonArray getRemoteFileList() throws Throwable {
	String url = "https://redunda.sobotics.org/bots/data.json?key="+this.apiKey;
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	//add request header
	con.setRequestMethod("GET");
	con.setRequestProperty("User-Agent", UserAgent.getUserAgent());
	
	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();
	
	String responseString = response.toString();
	//System.out.println(responseString);
	
	//http://stackoverflow.com/a/15116323/4687348
	JsonParser jsonParser = new JsonParser();
	JsonArray array = (JsonArray)jsonParser.parse(responseString);
	return array;
	/*
	List<String> filenames = new ArrayList<String>();
	
	for (JsonElement element : array) {
		JsonObject elementObject = element.getAsJsonObject();
		String key = elementObject.get("key").getAsString();
		if (key != null) {
			String decodedKey = this.decodeFilename(key);
			filenames.add(decodedKey);
		}
	}
	
	return filenames;*/
}
 
开发者ID:SOBotics,项目名称:Redunda-lib-java,代码行数:50,代码来源:DataService.java

示例15: 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 f
    connection.setRequestProperty("MCBUser-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 :)
}
 
开发者ID:CyR1en,项目名称:Minecordbot,代码行数:37,代码来源:Metrics.java


注:本文中的javax.net.ssl.HttpsURLConnection.setRequestProperty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。