項(xiàng)目需要對(duì)接外部接口,將圖片文件流發(fā)送到外部接口,下面代碼就是HttpsURLConnection如何上傳文件流:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
/** * HttpsURLConnection上傳文件流 * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //本地圖片 java.io.File file = new java.io.File( "/Users/jikukalun/Pictures/id1.jpg" ); FileInputStream fileInputStream = new FileInputStream(file); //對(duì)接外部接口 String urlString = "************" ; URL url = new URL(urlString); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); // 設(shè)置是否向httpUrlConnection輸出,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在 // http正文內(nèi),因此需要設(shè)為true, 默認(rèn)情況下是false; con.setDoOutput( true ); // 設(shè)置是否從httpUrlConnection讀入,默認(rèn)情況下是true; con.setDoInput( true ); // 設(shè)定請(qǐng)求的方法為"POST",默認(rèn)是GET con.setRequestMethod( "POST" ); // Post 請(qǐng)求不能使用緩存 con.setUseCaches( false ); // 設(shè)定傳送的內(nèi)容類型是可序列化的java對(duì)象 // (如果不設(shè)此項(xiàng),在傳送序列化對(duì)象時(shí),當(dāng)WEB服務(wù)默認(rèn)的不是這種類型時(shí)可能拋java.io.EOFException) // con.setRequestProperty("Content-type", "application/x-java-serialized-object"); OutputStream out = con.getOutputStream(); //讀取本地圖片文件流 FileInputStream inputStream = new FileInputStream(file); byte [] data = new byte [ 2048 ]; int len = 0 ; int sum = 0 ; while ((len = inputStream.read(data)) != - 1 ) { //將讀取到的本地文件流讀取到HttpsURLConnection,進(jìn)行上傳 out.write(data, 0 , len); sum = len + sum; } System.out.println( "上傳圖片大小為:" + sum); out.flush(); inputStream.close(); out.close(); int code = con.getResponseCode(); //獲取post請(qǐng)求返回狀態(tài) System.out.println( "code=" + code + " url=" + url); if (code == 200 ) { InputStream inputStream2 = con.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream2.read(data)) != - 1 ) { bos.write(data, 0 , len); } inputStream2.close(); String content = bos.toString(); bos.close(); System.out.println( "result =" + content); //將返回的json格式的字符串轉(zhuǎn)化為json對(duì)象 JSONObject json = JSONObject.parseObject(content); try { System.out.println( "name=" + json.getString( "name" ) + ", people=" + json.getString( "people" ) + ", sex=" + json.getString( "sex" ) + ", id_number=" + json.getString( "id_number" ) + ", type=" + json.getString( "type" ) + ", address=" + json.getString( "address" ) + ", birthday=" + json.getString( "birthday" )); } catch (JSONException e) { e.printStackTrace(); } } //斷開HttpsURLConnection連接 con.disconnect(); } |
引用jar包:
1
2
3
4
5
6
7
|
import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; |
以上這篇HttpsURLConnection上傳文件流(實(shí)例講解)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。