日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

用apache的httpclient发请求和接受数据

發(fā)布時(shí)間:2023/12/2 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用apache的httpclient发请求和接受数据 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

此處發(fā)請(qǐng)求的是用httpclient4,請(qǐng)自己下載所需要的jar包。

發(fā)post請(qǐng)求,并得到數(shù)據(jù)。

?

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));//發(fā)post請(qǐng)求的參數(shù)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();//得到從服務(wù)器端返回的數(shù)據(jù)流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); } //在客戶端生成文件。更高效的做法是,在服務(wù)器端傳過來一個(gè)壓縮后的btye[],然后在客戶端解壓,減少傳輸數(shù)據(jù)。try {FileOutputStream fo1 = null;fo1 = new FileOutputStream(exportFilePath);fo1.write(b);}fo1.close();} catch (Exception e2) {e2.printStackTrace();}}

?

在action中接請(qǐng)求的方法export(),并返回?cái)?shù)據(jù)流

?

try {request.setCharacterEncoding("UTF-8");} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}response.setCharacterEncoding("UTF-8");String leeSmart = request.getParameter("leeSmart");//前臺(tái)傳過來的post參數(shù)byte[] b = null;try{List ret = serivce.query("select * from dual");//得到查詢結(jié)果集//將ret放到sb中StringBuilder sb = new StringBuilder();//.......對(duì)結(jié)果集進(jìn)行處理,并轉(zhuǎn)成字節(jié)數(shù)組 b = sb.toString().getByte();}catch(Exception e){e.printStackTrace();}//如果方便,可以把b字節(jié)數(shù)組壓縮一下,這樣傳的數(shù)據(jù)會(huì)比較小一些。//將字節(jié)數(shù)組放到response中,并返回到客戶端。try {response.reset();// 設(shè)置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{}

?


?

轉(zhuǎn)載于:https://www.cnblogs.com/suncoolcat/p/3295154.html

總結(jié)

以上是生活随笔為你收集整理的用apache的httpclient发请求和接受数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。