日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

从输入流中获取数据并以字节数组返回

發布時間:2025/3/20 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 从输入流中获取数据并以字节数组返回 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • import?java.io.ByteArrayOutputStream;?

  • ? import?java.io.InputStream;?
  • public?class?StreamTool?{?

  • ? /**?

  • *?從輸入流獲取數據?

  • *?@param?inputStream?

  • *?@return?

  • *?@throws?Exception?

  • */?

  • ? public?static?byte[]?readInputStream(InputStream?inputStream)?throws?Exception?{?

  • ? byte[]?buffer?=?new?byte[1024];?//你可以根據實際需要調整緩存大小?
  • ??
  • ? int?len?=?-1;?

  • ByteArrayOutputStream?outSteam?=?new?ByteArrayOutputStream();?
  • //以前我在學IO流時不寫下句buffer,結果操作文件中無任何內容?
  • ? while(?(len?=?inputStream.read(buffer))?!=?-1?){?

  • outSteam.write(buffer,?0,?len);?
  • ?}?

  • outSteam.close();?

  • inputStream.close();?

  • ?
  • ? return?outSteam.toByteArray();?

  • ?
  • ?}?

  • ?
  • ?}?
  • ?
  • ?通過Android客戶端上傳數據到服務器:可以上傳簡單的表單,也可以方便的上傳帶有附件的文件,此類遠遠比Android自身的HttpClient更高效、更易于使用?
  • import?java.io.DataOutputStream;?
  • ?
  • import?java.io.InputStream;?
  • ?
  • import?java.net.HttpURLConnection;?
  • ?
  • import?java.net.URL;?
  • ?
  • import?java.net.URLEncoder;?
  • ?
  • import?java.util.ArrayList;?
  • ?
  • import?java.util.List;?
  • ?
  • import?java.util.Map;?
  • ?
  • import?org.apache.http.HttpResponse;?
  • ?
  • import?org.apache.http.NameValuePair;?
  • ?
  • import?org.apache.http.client.HttpClient;?
  • ?
  • import?org.apache.http.client.entity.UrlEncodedFormEntity;?
  • ?
  • import?org.apache.http.client.methods.HttpPost;?
  • ?
  • import?org.apache.http.impl.client.DefaultHttpClient;?
  • ?
  • import?org.apache.http.message.BasicNameValuePair;?
  • ?
  • public?class?HttpRequester?{?
  • ?
  • /**?
  • ?
  • *?直接通過HTTP協議提交數據到服務器,實現如下面表單提交功能:?
  • ?
  • *?<FORM?METHOD=POST?ACTION="http://192.168.0.1:8080/test.do"?enctype="multipart/form-data">?
  • ?
  • <INPUT?TYPE="text"?NAME="name">?
  • ?
  • <INPUT?TYPE="text"?NAME="id">?
  • ?
  • <input?type="file"?name="p_w_picpathfile"/>?
  • ?
  • <input?type="file"?name="zip"/>?
  • ?
  • </FORM>?
  • ?
  • *?@param?actionUrl?上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,http://192.168.1.10:8080這樣的路徑測試)?
  • ?
  • *?@param?params?請求參數?key為參數名,value為參數值?
  • ?
  • *?@param?file?上傳文件?
  • ?
  • */?
  • ?
  • public?static?String?post(String?actionUrl,?Map<String,?String>?params,?FormFile[]?files)?{?
  • ?
  • try?{?
  • ?
  • String?BOUNDARY?=?"---------7d4a6d158c9";?//數據分隔線?
  • ?
  • String?MULTIPART_FORM_DATA?=?"multipart/form-data";?
  • ?
  • URL?url?=?new?URL(actionUrl);?
  • ?
  • HttpURLConnection?conn?=?(HttpURLConnection)?url.openConnection();?
  • ?
  • conn.setConnectTimeout(5*?1000);?
  • ?
  • conn.setDoInput(true);//允許輸入?
  • ?
  • conn.setDoOutput(true);//允許輸出?
  • ?
  • conn.setUseCaches(false);//不使用Cache?
  • ?
  • conn.setRequestMethod("POST");?
  • ?
  • conn.setRequestProperty("Connection",?"Keep-Alive");?
  • ?
  • conn.setRequestProperty("Charset",?"UTF-8");?
  • ?
  • conn.setRequestProperty("Content-Type",?MULTIPART_FORM_DATA?+?";?
  • ?
  • boundary="?+?BOUNDARY);?
  • ?
  • StringBuilder?sb?=?new?StringBuilder();?
  • ?
  • for?(Map.Entry<String,?String>?entry?:?params.entrySet())?{//構建表單字段內容?
  • ?
  • sb.append("--");?
  • ?
  • sb.append(BOUNDARY);?
  • ?
  • sb.append("\r\n");?
  • ?
  • sb.append("Content-Disposition:?form-data;?name=\""+?entry.getKey()?+?"\"\r\n\r\n");?
  • ?
  • sb.append(entry.getValue());?
  • ?
  • sb.append("\r\n");?
  • ?
  • }?
  • ?
  • DataOutputStream?outStream?=?new?DataOutputStream(conn.getOutputStream());?
  • ?
  • outStream.write(sb.toString().getBytes());//發送表單字段數據?
  • ?
  • for(FormFile?file?:?files){//發送文件數據?
  • ?
  • StringBuilder?split?=?new?StringBuilder();?
  • ?
  • split.append("--");?
  • ?
  • split.append(BOUNDARY);?
  • ?
  • split.append("\r\n");?
  • ?
  • split.append("Content-Disposition:?form-data;name=\""+?
  • ?
  • file.getFormname()+"\";filename=\""+?file.getFilname()?+?"\"\r\n");?
  • ?
  • split.append("Content-Type:?"+?file.getContentType()+"\r\n\r\n");?
  • ?
  • outStream.write(split.toString().getBytes());?
  • ?
  • if(file.getInStream()!=null){?
  • ?
  • byte[]?buffer?=?new?byte[1024];?
  • ?
  • int?len?=?0;?
  • ?
  • while((len?=?file.getInStream().read(buffer))!=-1){?
  • ?
  • outStream.write(buffer,?0,?len);?
  • ?
  • }?
  • ?
  • file.getInStream().close();?
  • ?
  • }else{?
  • ?
  • outStream.write(file.getData(),?0,?file.getData().length);?
  • ?
  • }?
  • ?
  • outStream.write("\r\n".getBytes());?
  • ?
  • }?
  • ?
  • byte[]?end_data?=?("--"?+?BOUNDARY?+?"--\r\n").getBytes();//數據結束標志?
  • ?
  • outStream.write(end_data);?
  • ?
  • outStream.flush();?
  • ?
  • int?cah?=?conn.getResponseCode();?
  • ?
  • if?(cah?!=?200)?throw?new?RuntimeException("請求url失敗");?
  • ?
  • InputStream?is?=?conn.getInputStream();?
  • ?
  • int?ch;?
  • ?
  • StringBuilder?b?=?new?StringBuilder();?
  • ?
  • while(?(ch?=?is.read())?!=?-1?){?
  • ?
  • b.append((char)ch);?
  • ?
  • }?
  • ?
  • outStream.close();?
  • ?
  • conn.disconnect();?
  • ?
  • return?b.toString();?
  • ?
  • }?catch?(Exception?e)?{?
  • ?
  • throw?new?RuntimeException(e);?
  • ?
  • }?
  • ?
  • }?
  • ?
  • /**?
  • ?
  • *?提交數據到服務器?
  • ?
  • *?@param?actionUrl?上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.cnblogs.com/guoshiandroid或http://192.168.1.10:8080這樣的路徑測試)?
  • ?
  • *?@param?params?請求參數?key為參數名,value為參數值?
  • ?
  • *?@param?file?上傳文件?
  • ?
  • */?
  • ?
  • public?static?String?post(String?actionUrl,?Map<String,?String>?params,?FormFile?file)?{?
  • return?post(actionUrl,?params,?new?FormFile[]{file});?
  • }?
  • ?
  • public?static?byte[]?postFromHttpClient(String?path,?Map<String,?String>?params,?String?encode)?throws?Exception{?
  • ?
  • List<NameValuePair>?formparams?=?new?ArrayList<NameValuePair>();//用于存放請求參數?
  • ?
  • for(Map.Entry<String,?String>?entry?:?params.entrySet()){?
  • ?
  • formparams.add(new?BasicNameValuePair(entry.getKey(),?entry.getValue()));?
  • ?
  • }?
  • ?
  • UrlEncodedFormEntity?entity?=?new?UrlEncodedFormEntity(formparams,?"UTF-8");?
  • HttpPost?httppost?=?new?HttpPost(path);?
  • ?
  • httppost.setEntity(entity);?
  • ?
  • HttpClient?httpclient?=?new?DefaultHttpClient();//看作是瀏覽器?
  • ?
  • HttpResponse?response?=?httpclient.execute(httppost);//發送post請求?
  • ?
  • return?StreamTool.readInputStream(response.getEntity().getContent());?
  • ?
  • }?
  • ?
  • /**?
  • ?
  • *?發送請求?
  • ?
  • *?@param?path?請求路徑?
  • ?
  • *?@param?params?請求參數?key為參數名稱?value為參數值?
  • ?
  • *?@param?encode?請求參數的編碼?
  • ?
  • */?
  • ?
  • public?static?byte[]?post(String?path,?Map<String,?String>?params,?String?encode)?throws?Exception{?
  • ?
  • //String?params?=?"method=save&name="+?URLEncoder.encode("國士工作室",?"UTF-8")+?"&age=28&";//需要發送的參數?
  • ?
  • StringBuilder?parambuilder?=?new?StringBuilder("");?
  • ?
  • if(params!=null?&&?!params.isEmpty()){?
  • ?
  • for(Map.Entry<String,?String>?entry?:?params.entrySet()){?
  • ?
  • parambuilder.append(entry.getKey()).append("=")?
  • ?
  • .append(URLEncoder.encode(entry.getValue(),?encode)).append("&");?
  • ?
  • }?
  • ?
  • parambuilder.deleteCharAt(parambuilder.length()-1);?
  • ?
  • }?
  • ?
  • byte[]?data?=?parambuilder.toString().getBytes();?
  • ?
  • URL?url?=?new?URL(path);?
  • ?
  • HttpURLConnection?conn?=?(HttpURLConnection)url.openConnection();?
  • ?
  • conn.setDoOutput(true);//允許對外發送請求參數?
  • ?
  • conn.setUseCaches(false);//不進行緩存?
  • ?
  • conn.setConnectTimeout(5?*?1000);?
  • ?
  • conn.setRequestMethod("POST");?
  • ?
  • //下面設置http請求頭?
  • ?
  • conn.setRequestProperty("Accept",?"p_w_picpath/gif,?p_w_picpath/jpeg,?p_w_picpath/pjpeg,?p_w_picpath/pjpeg,?application/x-shockwave-flash,?application/xaml+xml,?application/vnd.ms-xpsdocument,?application/x-ms-xbap,?application/x-ms-application,?application/vnd.ms-excel,?application/vnd.ms-powerpoint,?application/msword,?*/*");?
  • ?
  • conn.setRequestProperty("Accept-Language",?"zh-CN");?
  • ?
  • conn.setRequestProperty("User-Agent",?"Mozilla/4.0?(compatible;?MSIE?8.0;?Windows?NT?5.2;?Trident/4.0;?.NET?CLR?1.1.4322;?.NET?CLR?2.0.50727;?.NET?CLR?3.0.04506.30;?.NET?CLR?3.0.4506.2152;?.NET?CLR?3.5.30729)");?
  • ?
  • conn.setRequestProperty("Content-Type",?"application/x-www-form-urlencoded");?
  • ?
  • conn.setRequestProperty("Content-Length",?String.valueOf(data.length));?
  • ?
  • conn.setRequestProperty("Connection",?"Keep-Alive");?
  • ?
  • //發送參數?
  • ?
  • DataOutputStream?outStream?=?new?DataOutputStream(conn.getOutputStream());?
  • ?
  • outStream.write(data);//把參數發送出去?
  • ?
  • outStream.flush();?
  • ?
  • outStream.close();?
  • ?
  • if(conn.getResponseCode()==200){?
  • ?
  • return?StreamTool.readInputStream(conn.getInputStream());?
  • ?
  • }?
  • ?
  • return?null;?
  • ?
  • }?
  • ?
  • }?
  • ?
  • ??
  • ?

    轉載于:https://blog.51cto.com/mzh3344258/687233

    總結

    以上是生活随笔為你收集整理的从输入流中获取数据并以字节数组返回的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。