用apache的httpclient发请求和接受数据
生活随笔
收集整理的這篇文章主要介紹了
用apache的httpclient发请求和接受数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
此處發請求的是用httpclient4,請自己下載所需要的jar包。
發post請求,并得到數據。
?
String url = "http://localhost:8080/lee";url = url+ "/query/action/export.action";String exportFilePath = "lee"+".csv.";final HttpClient httpClient = new DefaultHttpClient();final HttpPost post = new HttpPost(url);List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("leeSmart", leeSmart));//發post請求的參數post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));final HttpResponse response = httpClient.execute(post);//得到返回的responsefinal int code = response.getStatusLine().getStatusCode();final HttpEntity entity = response.getEntity();//得到entityif (entity != null && code < 400) {InputStream inputStream = entity.getContent();//得到從服務器端返回的數據流long length = entity.getContentLength();if(length<=0) return;int len = (int)length;byte[] b = new byte[len];int readCount = 0;//建議用以下方式讀inputStream為b賦值while (readCount < len) { readCount += inputStream.read(b, readCount, len - readCount); } //在客戶端生成文件。更高效的做法是,在服務器端傳過來一個壓縮后的btye[],然后在客戶端解壓,減少傳輸數據。try {FileOutputStream fo1 = null;fo1 = new FileOutputStream(exportFilePath);fo1.write(b);}fo1.close();} catch (Exception e2) {e2.printStackTrace();}}?
在action中接請求的方法export(),并返回數據流
?
try {request.setCharacterEncoding("UTF-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}response.setCharacterEncoding("UTF-8");String leeSmart = request.getParameter("leeSmart");//前臺傳過來的post參數byte[] b = null;try{List ret = serivce.query("select * from dual");//得到查詢結果集//將ret放到sb中StringBuilder sb = new StringBuilder();//.......對結果集進行處理,并轉成字節數組 b = sb.toString().getByte();}catch(Exception e){e.printStackTrace();}//如果方便,可以把b字節數組壓縮一下,這樣傳的數據會比較小一些。//將字節數組放到response中,并返回到客戶端。try {response.reset();// 設置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + new String("random".getBytes("UTF-8"),"ISO-8859-1"));response.addHeader("Content-Length", "" + b.length);OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(b);toClient.flush();toClient.close();} catch (Exception e) {e.printStackTrace();}finally{}?
?
轉載于:https://www.cnblogs.com/suncoolcat/p/3295154.html
總結
以上是生活随笔為你收集整理的用apache的httpclient发请求和接受数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SharePoint 2010 技术参数
- 下一篇: 在wp中,使用NavigationSer