- public class HttpUtils {
-
-
- private static String url_path ="http://192.168.10.101:8080/myhttp/bg.jpg";
-
- public static void saveImageToDisk() {
- InputStream inputStream = null;
- inputStream = getInputStream();
- byte[] data = new byte[1024];
- int len = 0;
-
- FileOutputStream fileOutputStream = null;
- try {
- fileOutputStream = new FileOutputStream("D:\\test.jpg");
- while ((len = inputStream.read(data))!=-1) {
- fileOutputStream.write(data,0,len);
- }
-
- } catch (FileNotFoundException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- }finally{
- if(fileOutputStream!=null){
- try {
- fileOutputStream.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- if(inputStream!=null){
- try {
- inputStream.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }
-
-
-
- }
-
-
- public static InputStream getInputStream(){
- InputStream inputStream = null;
- HttpURLConnection httpURLConnection = null;
- try {
- URL url = new URL(url_path);
- if (url!=null) {
- httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setConnectTimeout(3000);
- httpURLConnection.setDoInput(true);
- httpURLConnection.setRequestMethod("GET");
- int responseCode = httpURLConnection.getResponseCode();
- if (responseCode == 200) {
-
- inputStream = httpURLConnection.getInputStream();
- }
- }
-
-
- } catch (MalformedURLException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- return inputStream;
-
- }
-
- public static void main(String[] args) {
-
- saveImageToDisk();
- }
-
- }
注:http的get方式提交請求的流程:
創建URL;
1)定義InputStream流對象,定義HttpUrlConnection對象;
2)用URL的openConnection函數打開鏈接返回HttpUrlConnection對象;
3)HttpUrlConnection對象的setConnectTimeOut函數設置鏈接超時時間;
4)HttpUrlConnection對象的setDoInput函數打開輸入流;
5)HttpUrlConnection對象的setRequestMethod函數設置鏈接方式,即GET或者POST方式;
6)HttpUrlConnection對象的getResponseCode函數返回鏈接結果,結果為int類型;
結果有這么幾種常見的可能:200,請求成功;404資源未找到;500,服務器內部錯誤;
詳見: http狀態碼/http返回碼詳解
二.服務器端
http://blog.csdn.net/u012702039/article/details/42224721
以上鏈接的基礎上,在WebContent文件夾下放置一個bg.jpg圖片,運行起來,作為服務器端。
如圖:
然后再運行客戶端程序,即可把服務器端的bg.jpg圖片保存為d盤的test.jpg文件。