java Httppost Content-Type: image/jpeg 上传图片封装方法
时间: 2023-06-26 15:09:15 浏览: 57
以下是Java中使用HttpPost上传图片的封装方法:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpUtil {
public static String uploadImage(String url, byte[] imageBytes) throws IOException {
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 创建图片ContentBody对象
ContentBody imageBody = new ByteArrayBody(imageBytes, ContentType.create("image/jpeg"), "image.jpg");
// 创建MultipartEntityBuilder对象,用于封装请求参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("image", imageBody); // 添加图片ContentBody对象
// 将参数封装到HttpEntity中
HttpEntity httpEntity = builder.build();
// 设置请求参数
httpPost.setEntity(httpEntity);
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 获取响应实体
HttpEntity entity = response.getEntity();
// 将响应实体转换为字符串
String result = EntityUtils.toString(entity, "UTF-8");
return result;
}
}
```
使用方法如下:
```java
byte[] imageBytes = ...; // 待上传的图片字节数组
String url = ...; // 上传图片的接口地址
try {
String result = HttpUtil.uploadImage(url, imageBytes);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
```
注意:代码中使用了Apache HttpClient库,需要将其添加到项目依赖中。