天成1 发表于 2015-11-14 00:23:57

用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(&quot;leeSmart&quot;, leeSmart));//发post请求的参数
post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
final HttpResponse response = httpClient.execute(post);//得到返回的response
final int code = response.getStatusLine().getStatusCode();
final HttpEntity entity = response.getEntity();//得到entity
if (entity != null && code < 400) {
InputStream inputStream = entity.getContent();//得到从服务器端返回的数据流
long length = entity.getContentLength();
if(length<=0) return;
int len = (int)length;
byte[] b = new byte;
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(&quot;UTF-8&quot;);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setCharacterEncoding(&quot;UTF-8&quot;);
String leeSmart = request.getParameter(&quot;leeSmart&quot;);//前台传过来的post参数
byte[] b = null;
try{
List ret = serivce.query(&quot;select * from dual&quot;);//得到查询结果集
//将ret放到sb中
StringBuilder sb = new StringBuilder();
//.......对结果集进行处理,并转成字节数组
                      b = sb.toString().getByte();
}catch(Exception e){
e.printStackTrace();
}
//如果方便,可以把b字节数组压缩一下,这样传的数据会比较小一些。
//将字节数组放到response中,并返回到客户端。
try {
                   response.reset();
                  // 设置response的Header
                   response.addHeader(&quot;Content-Disposition&quot;, &quot;attachment;filename=&quot; + new String(&quot;random&quot;.getBytes(&quot;UTF-8&quot;),&quot;ISO-8859-1&quot;));
                  response.addHeader(&quot;Content-Length&quot;, &quot;&quot; + b.length);
                  OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                  response.setContentType(&quot;application/octet-stream&quot;);
                  toClient.write(b);
                  toClient.flush();
                  toClient.close();
             } catch (Exception e) {
                e.printStackTrace();
             }finally{
             }


  




  

版权声明:paincupid博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: 用apache的httpclient发请求和接受数据