HttpClientUtil工具类

简介: HttpClientUtil工具类代码如下。
import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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 java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
  public static String doGet(String url, Map<String, String> param) {
    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String resultString = "";
    CloseableHttpResponse response = null;
    try {
      // 创建uri
      URIBuilder builder = new URIBuilder(url);
      if (param != null) {
        for (String key : param.keySet()) {
          builder.addParameter(key, param.get(key));
        }
      }
      URI uri = builder.build();
      // 创建http GET请求
      HttpGet httpGet = new HttpGet(uri);
      // 执行请求
      response = httpclient.execute(httpGet);
      // 判断返回状态是否为200
      if (response.getStatusLine().getStatusCode() == 200) {
        resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (response != null) {
          response.close();
        }
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return resultString;
  }
  public static String doGet(String url) {
    return doGet(url, null);
  }
  public static String doPost(String url, Map<String, Object> param) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建参数列表
      if (param != null) {
        List<NameValuePair> paramList = new ArrayList<>();
        for (String key : param.keySet()) {
          paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
        }
        // 模拟表单
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
        httpPost.setEntity(entity);
      }
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return resultString;
  }
  public static String doPost(String url) {
    return doPost(url, null);
  }
  public static String doPostJson(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPost.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return resultString;
  }
}


下载工具类(转载别人,地址没记,谢谢那位兄弟了)


public void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
    URL url = new URL(urlStr);  
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
                //设置超时间为3秒
    conn.setConnectTimeout(3*1000);
    //防止屏蔽程序抓取而返回403错误
    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    //得到输入流
    InputStream inputStream = conn.getInputStream();  
    //获取自己数组
    byte[] getData = readInputStream(inputStream);    
    //文件保存位置
    File saveDir = new File(savePath);
    if(!saveDir.exists()){
      saveDir.mkdir();
    }
    File file = new File(saveDir+File.separator+fileName);    
    FileOutputStream fos = new FileOutputStream(file);     
    fos.write(getData); 
    if(fos!=null){
      fos.close();  
    }
    if(inputStream!=null){
      inputStream.close();
    }
    System.out.println("info:"+url+" download success"); 
  }
  /**
   * 从输入流中获取字节数组
   * @param inputStream
   * @return
   * @throws IOException
   */
  public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
    byte[] buffer = new byte[1024];  
    int len = 0;  
    ByteArrayOutputStream bos = new ByteArrayOutputStream();  
    while((len = inputStream.read(buffer)) != -1) {  
      bos.write(buffer, 0, len);  
    }  
    bos.close();  
    return bos.toByteArray();  
  }  


相关文章
|
4月前
|
Android开发
SharePreference封装成工具类
SharePreference封装成工具类
133 1
|
7月前
|
JSON 网络协议 C#
C# 工具类
C# 工具类
47 1
|
7月前
|
Java
JavaMap工具类(MapUtils)
JavaMap工具类(MapUtils)
|
数据采集 算法 安全
一天一个 JUC 工具类 -- 真工具类
CountDownLatch CyclicBarrier ForkJoin Semaphore 使用方法和注意事项
|
7月前
JsonUtil工具类
JsonUtil工具类
34 0
工具类-HttpClientUtil
工具类-HttpClientUtil
51 0
|
搜索推荐 安全 小程序
6个十分好用的工具类网站
6个十分好用的工具类网站
188 0
6个十分好用的工具类网站
|
Java API 索引
【JUC基础】08. 三大工具类
JUC包中包含了三个非常实用的工具类:CountDownLatch(倒计数器),CyclicBarrier(循环栅栏),Semaphore(信号量)。
148 0
|
安全
CollectionUtils工具类的常用方法
集合判断:   例1: 判断集合是否为空:  CollectionUtils.isEmpty(null): true  CollectionUtils.isEmpty(new ArrayList()): true    CollectionUtils.
2061 0