http跨平台访问接口的post,get,及文件上传方式工具类(httpClient)

需要先引入工具类httpclient-4.5.jar,httpcore-4.4.6.jar

//--------------------------------------------------------------------------

package com.paifenle.risk.drools.util.comment;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
import java.util.Map.Entry;


import org.apache.http.Consts;
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;  
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;  
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;  
/**
 * 
 * @author Dabria_ly 2017年6月29日
 */
public class HttpClientUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);

// 默认的数据返回超时时间
private static final int defaultWaitingTimeOut = 60000;

// 默认的连接超时时间
private static final int defaultTimeOut = 60000;

public static void main(String[] args) {
Map<String, String> params = new HashMap<String, String>();
params.put("userId", "50073111");
String str =  HttpClientUtil.doPost("http://xxx.xx.x.xx:8080/Lendon/selectLendonScore", params, "UTF-8");
System.out.println(String.format("str=%s", str));

String url = new StringBuilder().append("http://xxx.xx.x.xx:8080/UserMix/getUserMix")
.append("?userId=").append("50073111")
.append("&currentId=").append("1000000901")
.toString();
String result = HttpClientUtil.doGet(url, "UTF-8");
System.out.println(String.format("result=%s", result));
}

/**
* http post
* @param url
* @param map
* @param charset
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String doPost(String url, Map<String, String> map, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
// 设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}

/**
* http get 请求

* @param url
* @param charset
* @param timeout
* @return
*/
public static String doGet(String url, String charset, int timeout) {


LOG.info("http get: url:{}", url);
String returnStr = null;


CloseableHttpClient httpClient = HttpClients.createDefault();


RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(defaultWaitingTimeOut) // 设置数据等待时间
.setConnectTimeout(timeout) // 设置连接超时时间
.build();


// 设置请求地址
HttpGet httpGet = new HttpGet(url);


CloseableHttpResponse httpResponse = null;
try {


httpGet.setConfig(requestConfig);
// 设置HttpPost数据
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
returnStr = EntityUtils.toString(httpEntity, charset);
}
}
} catch (Exception e) {
LOG.error("httpGet 异常" + e);
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
LOG.error("httpGet 连接关闭异常" + e);
}
}
}


return returnStr;
}

/**
* http get 请求

* @param url
* @param charset
* @return
*/
public static String doGet(String url, String charset) {
return doGet(url, charset, defaultTimeOut);
}

/**
 * 文件上传方式请求--OCR
 * @param url:请求路径
 * @param map:请求参数
 * @param image:文件全名
 * @param charset:字符集设置(UTF-8)
 * @return
 */
public String doUpload(String url,Map<String,Object> map,String image,String charset) { 
  String result = null;
  CloseableHttpClient httpClient = null;
           CloseableHttpResponse response = null;
           try {
              // httpClient = HttpClients.createDefault();
            httpClient = new SSLClient();
               
               // 把一个普通参数和文件上传给下面这个地址 是一个servlet
               HttpPost httpPost = new HttpPost(url);
               
              // 把文件转换成流对象FileBody
               FileBody bin = null;
              // URL mURL = new URL(image);
               try {
                // File fi = new File("http://obojjnevn.bkt.clouddn.com"+File.separator+mURL.getFile());
                //File fi = new File("E:/img/10032016082619152300000.jpg");
            bin = new FileBody(new File(image));
} catch (Exception e) {
e.printStackTrace();
}
             
               //FileBody bin = new FileBody(image);
  
              StringBody api_key = new StringBody(map.get("api_key").toString(), ContentType.create(
                      "text/plain", Consts.UTF_8));
              StringBody password = new StringBody(map.get("api_secret").toString(), ContentType.create(
                     "text/plain", Consts.UTF_8));
 
              HttpEntity reqEntity = MultipartEntityBuilder.create()
                     // 相当于<input type="file" name="file"/>
                      .addPart("image", bin)
                    
                      // 相当于<input type="text" name="userName" value=userName>
                     .addPart("api_key", api_key)
                      .addPart("api_secret", password)
                     .build();
              httpPost.setEntity(reqEntity);
  
             // 发起请求 并返回请求的响应
              response = httpClient.execute(httpPost);
              
              LOG.info("The response value of token--->" + response.getFirstHeader("token"));
                  
              // 获取响应对象
              HttpEntity resEntity = response.getEntity();
              if (resEntity != null) {
               result =EntityUtils.toString(resEntity,charset); 
                  // 打印响应长度
               LOG.info("Response content length---> " + resEntity.getContentLength());
                  // 打印响应内容
                 // System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
               LOG.info("Response content--->" +result);
              }
              
              // 销毁
              EntityUtils.consume(resEntity);
          }catch (Exception e){
              e.printStackTrace();
         }finally {
              try {
                  if(response != null){
                      response.close();
                  }
              } catch (IOException e) {
                  e.printStackTrace();
             }
              
              try {
                  if(httpClient != null){
                      httpClient.close();
                  }
             } catch (IOException e) {
                  e.printStackTrace();
              }
          }
           return result;
   }


}

//----------------------------------------------------------------------------------------------

package com.paifenle.risk.drools.util.comment;


import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
import javax.net.ssl.SSLContext;  
import javax.net.ssl.TrustManager;  
import javax.net.ssl.X509TrustManager;  
import org.apache.http.conn.ClientConnectionManager;  
import org.apache.http.conn.scheme.Scheme;  
import org.apache.http.conn.scheme.SchemeRegistry;  
import org.apache.http.conn.ssl.SSLSocketFactory;  
import org.apache.http.impl.client.DefaultHttpClient; 


/** 

* @author Dabria_ly 2017年6月29日  
*/
public class SSLClient extends DefaultHttpClient{ 
public SSLClient() throws Exception{  
       super();  
       SSLContext ctx = SSLContext.getInstance("TLS");  
       X509TrustManager tm = new X509TrustManager() {  
               @Override  
               public void checkClientTrusted(X509Certificate[] chain,  
                       String authType) throws CertificateException {  
               }  
               @Override  
               public void checkServerTrusted(X509Certificate[] chain,  
                       String authType) throws CertificateException {  
               }  
               @Override  
               public X509Certificate[] getAcceptedIssuers() {  
                   return null;  
               }  
       };  
       ctx.init(null, new TrustManager[]{tm}, null);  
       SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
       ClientConnectionManager ccm = this.getConnectionManager();  
       SchemeRegistry sr = ccm.getSchemeRegistry();  
       sr.register(new Scheme("https", 443, ssf));  
   }}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 HttpClient 进行文件下载的工具类示例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class FileDownloadUtil { private static final int TIMEOUT_CONNECTION = 5000; // 连接超时时间 private static final int TIMEOUT_SOCKET = 5000; // 读取超时时间 public static boolean downloadFile(String url, String filePath) { HttpClient httpClient = null; HttpGet httpGet = null; try { httpClient = getHttpClient(); httpGet = new HttpGet(url); HttpEntity httpEntity = httpClient.execute(httpGet).getEntity(); if (httpEntity != null) { FileOutputStream fos = new FileOutputStream(new File(filePath), false); fos.write(EntityUtils.toByteArray(httpEntity)); fos.flush(); fos.close(); return true; } } catch (IOException e) { e.printStackTrace(); } finally { if (httpGet != null) { httpGet.abort(); } if (httpClient != null) { ClientConnectionManager mgr = httpClient.getConnectionManager(); if (mgr != null) { mgr.shutdown(); } } } return false; } private static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); return new DefaultHttpClient(params); } } ``` 使用示例: ```java String url = "http://example.com/example.pdf"; String filePath = "/path/to/file/example.pdf"; boolean success = FileDownloadUtil.downloadFile(url, filePath); if (success) { System.out.println("文件下载成功!"); } else { System.out.println("文件下载失败!"); } ``` 需要注意的是,在使用 HttpClient 进行网络请求时,需要在 AndroidManifest.xml 文件中添加网络访问权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值