HTTPclient 4.2.2 传参数和文件流
Posted woshuaile
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTPclient 4.2.2 传参数和文件流相关的知识,希望对你有一定的参考价值。
package com.http; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.junit.Test; public class HttpClientUtil { @Test public void testHttp() { //创建HttpClient对象 HttpClient client = new DefaultHttpClient(); //构建POST请求 请求地址请更换为自己的。 //1) HttpPost post = new HttpPost("XX"); File file=new File("C:\Users\admin\Desktop\xidada.jpg"); FileBody fileBody=new FileBody(file); try { StringBody name = new StringBody("xidada.jpg"); MultipartEntity reqEntity = new MultipartEntity(); StringBody bucketId = new StringBody("402880bd66a545e90166a545f3700000"); reqEntity.addPart("bucketId", bucketId);//对应接口端的参数名称 reqEntity.addPart("name", name); reqEntity.addPart("file", fileBody);//file1为请求后台的File upload;属性 post.setEntity(reqEntity); HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ System.out.println("服务器正常响应....."); HttpEntity resEntity = response.getEntity(); System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据 System.out.println(resEntity.getContent()); EntityUtils.consume(resEntity); } }catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
以上是关于HTTPclient 4.2.2 传参数和文件流的主要内容,如果未能解决你的问题,请参考以下文章
java 怎么根据httpPost 和httpClient 等,传图片到服务器!
.NET Core Web API使用HttpClient提交文件的二进制流(multipart/form-data内容类型)