123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package cn.hhj.util;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.auth.AuthScope;
- import org.apache.http.auth.Credentials;
- import org.apache.http.auth.UsernamePasswordCredentials;
- import org.apache.http.client.CredentialsProvider;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.protocol.HttpClientContext;
- import org.apache.http.entity.ContentType;
- import org.apache.http.entity.mime.MultipartEntityBuilder;
- import org.apache.http.impl.client.BasicCredentialsProvider;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- import org.springframework.web.multipart.MultipartFile;
- import java.nio.charset.Charset;
- public class RemoteUploadUtil {
- public static String remoteupload(MultipartFile photo, String UPLOAD_URL) throws Exception {
- if (photo != null) {
- //创建一个httpClient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- // 创建Http处理操作的上下文对象
- HttpClientContext httpContext = HttpClientContext.create();
- // 设置认证的提供信息
- // httpContext.setCredentialsProvider(credsProvider);
- // 设置要进行访问的请求地址
- HttpPost httpPost = new HttpPost(UPLOAD_URL);
- HttpEntity entity = MultipartEntityBuilder.create()
- .addBinaryBody("photo", photo.getBytes(),
- ContentType.create("image/jpeg"), "temp.jpg").build();
- // 设置要发送的实体内容
- httpPost.setEntity(entity);
- // 执行请求的发送
- HttpResponse response = httpClient.execute(httpPost, httpContext);
- //取得返回的内容
- return EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
- }
- return "error.jpg";
- }
- public String remoteupload(String username, String password, MultipartFile photo, String UPLOAD_URL) throws Exception {
- if (photo != null) {
- //创建一个httpClient对象
- CloseableHttpClient httpClient = HttpClients.createDefault();
- //创建一个具有认证访问的信息
- CredentialsProvider credsProvider = new BasicCredentialsProvider();
- // 创建一条认证操作信息
- Credentials credentials = new UsernamePasswordCredentials("QingSe", "hello");
- // 现在所有的认证请求都使用一个认证信息
- credsProvider.setCredentials(AuthScope.ANY, credentials);
- // 创建Http处理操作的上下文对象
- HttpClientContext httpContext = HttpClientContext.create();
- // 设置认证的提供信息
- httpContext.setCredentialsProvider(credsProvider);
- // 设置要进行访问的请求地址
- HttpPost httpPost = new HttpPost(UPLOAD_URL);
- HttpEntity entity = MultipartEntityBuilder.create()
- .addBinaryBody("photo", photo.getBytes(),
- ContentType.create("image/jpeg"), "temp.jpg").build();
- // 设置要发送的实体内容
- httpPost.setEntity(entity);
- // 执行请求的发送
- HttpResponse response = httpClient.execute(httpPost, httpContext);
- //取得返回的内容
- return EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
- }
- return "error.jpg";
- }
- }
|