繼選擇圖片相冊并通過ImageView展示在Activity中,獲取到圖片真實路徑后(詳見Android獲取相冊中圖片的路徑 4.4版本前后的變化),
將通過以下兩種方式(當然了不止這兩種)將獲取到的圖片上傳到服務端,僅涉及客戶端代碼部分。
使用HttpURLConnection的方式模擬拼裝HTTP請求使用HttpClient(6.0已經廢棄了HttpClient,但是還有有必要記錄下)
本篇博客將主要記錄第一種方式,下篇將記錄第二種方式。
主要是模擬HTTP請求,以及流的處理。
核心代碼如下,詳情請移步本人GITHUB
try {URL httpURL =
new URL(url);HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection();
/**設置connection屬性 ,拼裝HTTP請求協議**/connection.setDoInput(
true);connection.setDoOutput(
true);connection.setUseCaches(
false);connection.setRequestMethod(
"POST");connection.setReadTimeout(
5 *
1000);connection.setConnectTimeout(
5 *
1000);connection.setRequestProperty(
"Connection",
"Keep-Alive");connection.setRequestProperty(
"Charset",
"UTF-8");connection.setRequestProperty(
"Content-Type", CONTENT_TYPE +
"; boundary=" + BOUNDARY);DataOutputStream ds =
new DataOutputStream(connection.getOutputStream());
/** 模擬拼裝請求正文頭 在瀏覽器開發者工具中F12網絡中可以查看-----------------------------7df2cd15150370 (這個BOUNDARY比請求頭的多--,所以定義了個prefix)Content-Disposition: form-data; name="file"; filename="C:\Users\Mr.Yang\Desktop\girl.jpg"Content-Type: image/jpeg-----------------------------7df2cd15150370--**/ds.writeBytes(PREFIX + BOUNDARY + LINE_END);ds.writeBytes(
"Content-Disposition: form-data; "+
"name=\"file\";filename=\"" + file.getName() +
"\"" + LINE_END);ds.writeBytes(LINE_END);FileInputStream fis =
new FileInputStream(file);
byte[] buffer =
new byte[
1024 *
4];
int len = -
1;
while ((len = fis.read(buffer)) != -
1) {ds.write(buffer,
0, len);}ds.writeBytes(LINE_END);ds.writeBytes(PREFIX + BOUNDARY + PREFIX + LINE_END);ds.flush();
/** 接收服務端的返回信息**/BufferedReader reader =
new BufferedReader(
new InputStreamReader(connection.getInputStream()));StringBuffer sb =
new StringBuffer();String line;
while ((line = reader.readLine()) !=
null) {sb.append(line);}LogUtils.d(
"服務端返回:" + sb.toString());
if (fis !=
null) {fis.close();}
if (reader !=
null) {reader.close();}
if (ds !=
null) {ds.close();}Message message =
new Message();message.what =
1;message.obj = sb.toString();handler.sendMessage(message);}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
總結
以上是生活随笔為你收集整理的Android-上传图片(-)_HttpURLConnection的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。