HttpClient4 基本操作
来源:互联网 发布:五五开这个人 知乎 编辑:程序博客网 时间:2024/06/05 05:05
文件上传
/** * 上传文件 * * @throws ParseException * @throws IOException */ public static void postFile() throws ParseException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 要上传的文件的路径 String filePath = new String("C:\\Users\\zz\\Desktop\\diqu.png"); // 把一个普通参数和文件上传给下面这个地址 是一个servlet HttpPost httpPost = new HttpPost( "http://xx.xx.xx.xxs:8081/auth_center/upload"); // 把文件转换成流对象FileBody File file = new File(filePath); FileBody bin = new FileBody(file); /*StringBody uploadFileName = new StringBody("my.png", ContentType.create("text/plain", Consts.UTF_8));*/ // 以浏览器兼容模式运行,防止文件名乱码。 HttpEntity reqEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("uploadFile", bin) // uploadFile对应服务端类的同名属性<File类型> //.addPart("uploadFileName", uploadFileName)// uploadFileName对应服务端类的同名属性<String类型> .setCharset(CharsetUtils.get("UTF-8")).build(); httpPost.setEntity(reqEntity); System.out.println("发起请求的页面地址 " + httpPost.getRequestLine()); // 发起请求 并返回请求的响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { // 打印响应状态 System.out.println(response.getStatusLine()); // 获取响应对象 HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // 打印响应长度 System.out.println("Response content length: " + resEntity.getContentLength()); // 打印响应内容 System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8"))); } // 销毁 EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpClient.close(); } }
文件下载
/** * 下载文件 * * @param url * http://www.xxx.com/img/333.jpg * @param destFileName * xxx.jpg/xxx.png/xxx.txt * @throws ClientProtocolException * @throws IOException */ public static void getFile(String url, String destFileName) throws ClientProtocolException, IOException { // 生成一个httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); File file = new File(destFileName); try { FileOutputStream fout = new FileOutputStream(file); int l = -1; byte[] tmp = new byte[1024]; while ((l = in.read(tmp)) != -1) { fout.write(tmp, 0, l); // 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试 } fout.flush(); fout.close(); } finally { // 关闭低层流。 in.close(); } httpclient.close(); }
读取压缩文件
public static void readZipFile(String file) throws Exception { ZipFile zf = new ZipFile(file); InputStream in = new BufferedInputStream(new FileInputStream(file)); ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { if (ze.isDirectory()) { } else { System.err.println("file - " + ze.getName() + " : " + ze.getSize() + " bytes"); long size = ze.getSize(); if (size > 0) { BufferedReader br = new BufferedReader( new InputStreamReader(zf.getInputStream(ze))); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } System.out.println(); } } zin.closeEntry(); }
Post Json数据
HttpPost httpPost = new HttpPost(url);StringEntity stringEntity = new StringEntity(json.toString());stringEntity.setContentType("application/json");httpPost.setEntity(stringEntity);
示例:
public static String httpPostWithJSON(String url) throws Exception { HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null;// json方式 JSONObject jsonParam = new JSONObject(); jsonParam.put("name", "admin"); jsonParam.put("pass", "123456"); StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题 entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); System.out.println();// 表单方式// List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); // pairList.add(new BasicNameValuePair("name", "admin"));// pairList.add(new BasicNameValuePair("pass", "123456"));// httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); HttpResponse resp = client.execute(httpPost); if(resp.getStatusLine().getStatusCode() == 200) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he,"UTF-8"); } return respContent; } public static void main(String[] args) throws Exception { String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc"); System.out.println(result); }
0 0
- 【HttpClient4】 基本操作
- HttpClient4 基本操作
- HTTPClient4
- HttpClient4
- 01.使用httpclient4 操作 12306 之 登录篇
- 基本操作
- 基本操作
- 基本操作
- 基本操作
- 基本操作
- 基本操作
- 基于HttpClient4.0的网络爬虫基本框架(Java实现)
- 基于HttpClient4.0的网络爬虫基本框架(Java实现)
- 【JAVA】基于HttpClient4.0的网络爬虫基本框架(Java实现)
- sparkSQL操作基本操作
- HttpClient4使用
- HttpClient4.0
- Httpclient4 简介
- 我害怕阅读的人
- Unix:线程池的例子
- Nginx代码解析
- 贪心算法—Problem A
- 点击动画 波纹效果 主要用来做引导动画
- HttpClient4 基本操作
- 关于C++学习
- 一篇基于pthon和scikt-learn的关于机器学习的介绍
- hrbust 哈理工oj 1989 营救小组【BFS】
- 使用jdbclogger将所有sql完整的打印出来
- 希尔排序
- HDU 3068_求最大回文串_manacher算法_O(n)
- LeetCode: Factorial Trailing Zeroes
- HDU 2010 水仙花数