http访问接口post和get方法类

远程访问接口get和post方法。

引用的包


    org.apache.httpcomponents
    httpclient
    4.5.2



    org.apache.httpcomponents
    httpmime
    4.5.2

代码 

package com.bingo.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


/**
 * HTTP接口工具类
 * {@link HttpUtils}
 *
 * DONE : 调用http接口工具类
 *
 * @author shenlu
 */
public class HttpUtils {
   private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

   /**
    * httpget调用http接口
    * @param url
    * @param jsonStr
    * @param t
    * @param 
    * @return
    * @throws IOException
    * @throws IllegalAccessException
    * @throws InstantiationException
    */
   public static T httpGet(String url, String jsonStr,Class t)throws IOException, IllegalAccessException, InstantiationException {
      HttpResponse response = null;
      JSONObject jsonObject = null;
      T instance = t.newInstance();
      String result="";
      try {
         if(url==null||"".equals(url)){
            throw new Exception("接口调用接口方法不能为空!");
         }
         //创建httpClient实例
         CloseableHttpClient httpClient = HttpClients.createDefault();
         //创建实例方法
         HttpGet httpget = new HttpGet(url);
         httpget.addHeader("Content-Type", "text/plain;charset=UTF-8");
         response = httpClient.execute(httpget);

         if(response.getStatusLine().getStatusCode()==200){//如果状态码为200,就是正常返回
            result=EntityUtils.toString(response.getEntity(),"UTF-8");
         }
         jsonObject =JSON.parseObject(result);
         if(instance instanceof JSONObject) {
            return (T) jsonObject;
         }

         T resultBean = (T) JSONObject.parseObject(jsonObject.toString(), t);
         return resultBean;
      } catch (ConnectException ce) {
         log.error(url+"接口 --server connection timed out:{}",ce);
         ce.printStackTrace();
      } catch (Exception e) {
         log.error(url+"--接口异常--",e);
         e.printStackTrace();
      }
      return t.newInstance();
   }

    /**
     *
     * @param url
     * @param jsonStr
     * @param t
     * @param 
     * @throws IOException
     */
   public static T  httpPost(String url, String jsonStr,Class t) throws IOException, IllegalAccessException, InstantiationException {
      JSONObject jsonObject = null;
      HttpResponse response = null;
      //创建httpClient实例
      CloseableHttpClient httpClient = HttpClients.createDefault();
        T instance = t.newInstance();
      try {

         if(url==null||"".equals(url)){
            throw new Exception("接口调用接口方法不能为空!");
         }
         //创建实例方法
         HttpPost httppost = new HttpPost(url);
         httppost.addHeader("Content-Type", "application/json;charset=UTF-8");
         //设置连接超时时间和数据获取超时时间--单位:ms
         RequestConfig requestConfig = RequestConfig.custom()  
                 .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                 .setSocketTimeout(5000).build();
         httppost.setConfig(requestConfig);
           //设置http request body请求体
            if (null != jsonStr) {
                //解决中文乱码问题
               StringEntity myEntity = new StringEntity(jsonStr, "UTF-8");
               httppost.setEntity(myEntity); 
            }
            response = httpClient.execute(httppost);

         String result=EntityUtils.toString(response.getEntity(),"UTF-8");
         log.info("返回结果:"+result);
         //得到返回的字符串
          jsonObject =JSON.parseObject(result);
          if(instance instanceof JSONObject) {
             return (T) jsonObject;
          }

         T resultBean = (T) JSONObject.parseObject(jsonObject.toString(), t);
         return resultBean;
      } catch (ConnectException ce) {
         log.error(url+"接口 --server connection timed out:{}",ce);
         ce.printStackTrace();
      } catch (Exception e) {
         log.error(url+"--接口异常--",e);
         e.printStackTrace();
      }finally{
         httpClient.close();
      }
        return t.newInstance();
   }

   /**
    *
    * @param urlStr
    * @param map
    * @param t
    * @param 
    * @return
    * @throws IOException
    * @throws IllegalAccessException
    * @throws InstantiationException
    */
   public static T  httpFormDataPost(String urlStr, Map map, Class t) throws IllegalAccessException, InstantiationException {
      JSONObject jsonObject = null;
      T instance = t.newInstance();
      String result="";
      // 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
      String BOUNDARY = "----------HV2ymHFg03ehbqgZCaKO6jyH";
      HttpURLConnection conn = null;
      try {
         if(urlStr==null||"".equals(urlStr)){
            throw new Exception("接口调用接口方法不能为空!");
         }
         URL url=new URL(urlStr);
         conn = (HttpURLConnection)url.openConnection();
         conn.setConnectTimeout(5000);
         conn.setReadTimeout(30000);
         conn.setDoOutput(true);
         conn.setDoInput(true);
         conn.setUseCaches(false);
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

         // 头
         String boundary = BOUNDARY;
         // 传输内容
         StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
         // 尾
         String endBoundary = "\r\n--" + boundary + "--\r\n";
         OutputStream out = conn.getOutputStream();

         // 1. 处理文字形式的POST请求
         for (Map.Entry entry : map.entrySet()) {
            contentBody.append("\r\n")
            .append("Content-Disposition: form-data; name=\"")
            .append(entry.getKey() + "\"")
            .append("\r\n")
            .append("\r\n")
            .append(entry.getValue())
            .append("\r\n")
            .append("--")
            .append(boundary);
         }
         String boundaryMessage1 = contentBody.toString();
         out.write(boundaryMessage1.getBytes("utf-8"));
         out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n"
               .getBytes("UTF-8"));

         // 3. 写结尾
         out.write(endBoundary.getBytes("utf-8"));
         out.flush();
         out.close();

         // 读取返回数据
         StringBuffer strBuf = new StringBuffer();
         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line = null;
         while ((line = reader.readLine()) != null) {
            strBuf.append(line).append("\n");
         }
         result = strBuf.toString();
         log.info("返回结果:"+result);
         reader.close();
         reader = null;
         jsonObject =JSON.parseObject(result);
         if(instance instanceof JSONObject) {
            return (T) jsonObject;
         }
         T resultBean = (T) JSONObject.parseObject(jsonObject.toString(), t);
         return resultBean;
      } catch (ConnectException ce) {
         log.error(urlStr+"接口 --server connection timed out:{}",ce);
         ce.printStackTrace();
      } catch (Exception e) {
         log.error(urlStr+"--接口异常--",e);
         e.printStackTrace();
      } finally {
         if (conn != null) {
            conn.disconnect();
            conn = null;
         }
      }
      return t.newInstance();
   }

   /**
    * 上传多媒体
    * @param urlStr
    * @param file
    * @param fileitem
    * @param t
    * @param 
    * @return
    * @throws IllegalAccessException
    * @throws InstantiationException
    */
   public static T postformUpload(String urlStr, File file, FileItem fileitem,Class t) throws IllegalAccessException, InstantiationException{
      JSONObject jsonObject = null;
      T instance = t.newInstance();
      String result="";
      HttpURLConnection conn = null;
      String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
      try {
         URL url=new URL(urlStr);
         conn = (HttpURLConnection)url.openConnection();
         conn.setConnectTimeout(5000);
         conn.setReadTimeout(30000);
         conn.setDoOutput(true);
         conn.setDoInput(true);
         conn.setUseCaches(false);
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

         OutputStream out = new DataOutputStream(conn.getOutputStream());
         if (fileitem != null|| file!=null) {
            String fileName = null;
            if(fileitem != null)
               fileName = fileitem.getName();
            if(file != null)
               fileName = file.getName();

            String contentType = "multipart/form-data";//match.getMimeType();

            StringBuffer strBuf = new StringBuffer();
            strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            strBuf.append("Content-Disposition: form-data; name=\"media\"; filename=\"" + fileName + "\"\r\n");
            strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
            DataInputStream in = null;
            out.write(strBuf.toString().getBytes());
            if(fileitem != null)
               in = new DataInputStream(fileitem.getInputStream());
            if(file != null)
               in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
               out.write(bufferOut, 0, bytes);
            }
            in.close();
         }
         byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
         out.write(endData);
         out.flush();
         out.close();

         // 读取返回数据
         StringBuffer strBuf = new StringBuffer();
         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         String line = null;
         while ((line = reader.readLine()) != null) {
            strBuf.append(line).append("\n");
         }
         result = strBuf.toString();
         reader.close();
         reader = null;
         jsonObject =JSON.parseObject(result);
         if(instance instanceof JSONObject) {
            return (T) jsonObject;
         }
         T resultBean = (T) JSONObject.parseObject(jsonObject.toString(), t);
         return resultBean;
      } catch (ConnectException ce) {
         log.error(urlStr+"接口 --server connection timed out:{}",ce);
         ce.printStackTrace();
      } catch (Exception e) {
         log.error(urlStr+"--接口异常--",e);
         e.printStackTrace();
      } finally {
         if (conn != null) {
            conn.disconnect();
            conn = null;
         }
      }
      return t.newInstance();
   }
}

 

你可能感兴趣的:(框架)