特别注意: HttpURLConnection要使用sun.net.www.protocol.http.HttpURLConnection
参考地址:http://ferreousbox.javaeye.com/blog/157728
代码如下:
1 FileInputStream fis =new FileInputStream(new File("本地文件地址"));
2 URL dataUrl = new URL("上传url");
3 HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();
4 con.setRequestMethod("POST");
5 con.setRequestProperty("Proxy-Connection", "Keep-Alive");
6 con.setDoOutput(true);
7 con.setDoInput(true);
8 con.setChunkedStreamingMode(1024);
9 OutputStream os=con.getOutputStream();
10 int rn2;
11 byte[] buf2 = new byte[1024];
12 while((rn2=fis.read(buf2, 0, 1024))>0)
13 {
14 os.write(buf2,0,rn2);
15 System.out.println("上传了1024...");
16 }
17 os.flush();
18 os.close();
19 fis.close();
20
21 InputStream is=con.getInputStream();
22 DataInputStream dis=new DataInputStream(is);
23 byte d[]=new byte[dis.available()];
24 dis.read(d);
25 String data=new String(d);
26 con.disconnect();
27 System.out.println(data);
2 URL dataUrl = new URL("上传url");
3 HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();
4 con.setRequestMethod("POST");
5 con.setRequestProperty("Proxy-Connection", "Keep-Alive");
6 con.setDoOutput(true);
7 con.setDoInput(true);
8 con.setChunkedStreamingMode(1024);
9 OutputStream os=con.getOutputStream();
10 int rn2;
11 byte[] buf2 = new byte[1024];
12 while((rn2=fis.read(buf2, 0, 1024))>0)
13 {
14 os.write(buf2,0,rn2);
15 System.out.println("上传了1024...");
16 }
17 os.flush();
18 os.close();
19 fis.close();
20
21 InputStream is=con.getInputStream();
22 DataInputStream dis=new DataInputStream(is);
23 byte d[]=new byte[dis.available()];
24 dis.read(d);
25 String data=new String(d);
26 con.disconnect();
27 System.out.println(data);
取返回值用下在这种方法会更好一点,上面的发现常出现取不到返回值的情况
代码
BufferedReader inss = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
StringBuffer content= new StringBuffer();
while((line = inss.readLine()) != null){//line为返回值,这就可以判断是否成功、
content.append(line);
}
inss.close() ;
inss=null;
dataUrl = null;
String data =content.toString();
String line = null;
StringBuffer content= new StringBuffer();
while((line = inss.readLine()) != null){//line为返回值,这就可以判断是否成功、
content.append(line);
}
inss.close() ;
inss=null;
dataUrl = null;
String data =content.toString();