AndroidTools Git地址: https://github.com/wisesun7/AndroidTools.git
????本篇通过HTTP的POST方式将数据上传到服务器中,需要的参数为URL(服务器地址),data(需上传的数据)。 这里简单介绍一下设置的一些属性:
- setRequsetMethod: 设置请求方式,GET和POST两种,上传一般使用POST,GET会有明文;
- setDoInput/Output : 使URL 连接可用于输入和/或输出;
- setConnectTimeout:设置连接超时时间;
- setRequestProperty: “Content-Type“是设置访问数据类型,"application/octet-stream"是指以流的形式传输,可以是任意类型,详细可参考http://tool.oschina.net/commons,其中标注了HTML的各种类型;
???? 另外,流和链接的关闭最好放在finally中,这样防止出现异常时的内存泄漏。
/*** @param url : 服务器地址* @param data : 上传的数据* @throws IOException*/private void uploadData(String url, byte[] data) throws IOException {
Log.d(TAG,"upload: " + url + ", length = " + data.length);HttpURLConnection connection = null;DataOutputStream out = null;try {
connection = (HttpURLConnection)(new URL(url)).openConnection();connection.setRequestMethod("POST");connection.setDoInput(true);connection.setDoOutput(true);connection.setConnectTimeout(6000);connection.setReadTimeout(6000);connection.setRequestProperty("Content-Type", "application/octet-stream");connection.connect();out = new DataOutputStream(connection.getOutputStream());out.write(data);out.flush();int responseCode = connection.getResponseCode();Log.d(TAG,url + " RESPONSE " + responseCode);if(responseCode != 200) {
throw new IOException("Response code: " + responseCode);}} finally {
if (out != null){
out.close();}if(connection != null) {
connection.disconnect();}}}