java請求get、post、put、delete方式封裝----三種實現方式

okhttp:

依賴:

<dependency>
	    <groupId>com.squareup.okhttp3</groupId>
	    <artifactId>okhttp</artifactId>
	    <version>3.14.2</version>
	</dependency>
package com.ece.manager.web.entranceGuardHK.util;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ece.manager.web.bluetoothLock.OkHttpUtils;


import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtil {
	private static final String Authorization = "bearer e45f6d0f-a863-425a-8d80-bd8821771046";
	
	private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json;charset=utf-8");
    private static final byte[] LOCKER = new byte[0];
    private static OkHttpUtil instance;
    private OkHttpClient okHttpClient;

    private OkHttpUtil() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)//10秒連接超時
                .writeTimeout(10, TimeUnit.SECONDS)//10m秒寫入超時
                .readTimeout(10, TimeUnit.SECONDS)//10秒讀取超時
                .build();
    }

    public static OkHttpUtil getInstance() {
        if (instance == null) {
            synchronized (LOCKER) {
                if (instance == null) {
                    instance = new OkHttpUtil();
                }
            }
        }
        return instance;
    }
    
    
    /**
     * 設置content-type
     * @param type
     * @return
     */
    public MediaType getMediaType(String type){
    	if(!type.equals("")){
    		return MediaType.parse(type);//"application/x-www-form-urlencoded; charset=utf-8"
    	}
		return MediaType.parse("application/json;charset=utf-8");
    }
    /**
     * delete請求 
     * @param url
     * @return
     */
    public String doDelete(String url){
        if (isBlankUrl(url)){
            return null;
        }
        Request request = getRequestForDelete(url);
        return commonRequest(request);
    }
    private Request getRequestForDelete(String url) {
        Request request = new Request.Builder()
        		.addHeader("Authorization", Authorization)
                .url(url)
                .delete(null)
                .build();
        return request;
    }

    /**
     * get請求 不帶參數
     * @param url
     * @return
     */
    public String doGet(String url){
        if (isBlankUrl(url)){
            return null;
        }
        Request request = getRequestForGet(url);
        return commonRequest(request);
    }
    /**
     * get請求 實現
     * @param url
     * @return
     */
    private Request getRequestForGet(String url) {
        Request request = new Request.Builder()
        		.addHeader("Authorization", Authorization)
                .url(url)
                .build();
        return request;
    }
    
    

    /**
     *  get請求 帶Map參數
     * @param url
     * @param params
     * @return
     */
    public String doGet(String url, Map<String, String> params){
    	System.out.println("參數^-^:"+params.toString());
        if (isBlankUrl(url)){
            return null;
        }
        Request request = getRequestForGet(url, params);
        return commonRequest(request);
    }
    /**
     * get請求 實現
     * @param url
     * @param params
     * @return
     */
    private Request getRequestForGet(String url, Map<String, String> params) {
        Request request = new Request.Builder()
        		.addHeader("Authorization", Authorization)
                .url(getUrlStringForGet(url, params))
                .build();
        return request;
    }

    
    /**
     * post請求  參數爲jsonStr
     * @param url
     * @param json
     * @param type
     * @return
     */
    public String doPostJson(String url, String json,String type){
        if (isBlankUrl(url)){
            return null;
        }
        Request request = getRequestForPostJson(url, json,type);
        return commonRequest(request);
    }
    
    /**
     *  實現post請求
     * @param url
     * @param json
     * @param type
     * @return
     */
    private Request getRequestForPostJson(String url, String json,String type) {
        RequestBody body = RequestBody.create(getMediaType(type), json);
        Request request = new Request.Builder()
        		.addHeader("Authorization", Authorization)
                .url(url)
                .post(body)
                .build();
        return request;
    }

    /**
     * 新post請求  參數爲map
     * @param url
     * @param params
     * @return
     */
    public String newDoPostForm(String url, Map<String, String> params,String type){
    	System.out.println("參數^-^:"+params.toString());
        if (isBlankUrl(url)) {
            return null;
        }
        Request request = getRequestForPostJson(url,  JSONObject.toJSONString(params),type);
        return commonRequest(request);
    }
    public String newsDoPostForm(String url, Map<String, Object> params,String type){
    	if(params!=null){
    		System.out.println("參數^-^:"+params.toString());
    	}
    	
        if (isBlankUrl(url)) {
            return null;
        }
        Request request = getRequestForPostJson(url,  JSONObject.toJSONString(params),type);
        return commonRequest(request);
    }
    
    /**
     * post請求  參數爲map
     * @param url
     * @param params
     * @return
     */
    public String doPostForm(String url, Map<String, String> params){
        if (isBlankUrl(url)) {
            return null;
        }
        Request request = getRequestForPostForm(url, params);
        return commonRequest(request);
    }
    /**
     * 實現post請求
     * @param url
     * @param params
     * @return
     */
    private Request getRequestForPostForm(String url, Map<String, String> params) {
        if (params == null) {
            params = new HashMap<>();
        }
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
        		.addHeader("Authorization", Authorization)
                .url(url)
                .post(requestBody)
                .build();
        return request;
    }
    private Boolean isBlankUrl(String url){
        if (StringUtils.isBlank(url)){
            System.out.println("url是null");
            return true;
        }else{
            return false;
        }
    }

    /**
     * 請求解析
     * @param request
     * @return
     */
    private String commonRequest(Request request){
        String re = "";
        try {
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            if (response.isSuccessful()){
                re = response.body().string();
                System.out.println("請求^-^:"+request.url().toString()+" \r\n響應^-^:"+re);
            }else {
            	System.out.println("請求失敗 url:"+request.url().toString()+"\r\nmessage:"+response.message());
            }
        }catch (Exception e){
        	System.out.println("請求異常"+e);
        }
        return re;
    }

   

    /**
     * get請求參數封裝
     * @param url
     * @param params
     * @return
     */
    private String getUrlStringForGet(String url, Map<String, String> params) {
    	int num = 0;
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(url);
        urlBuilder.append("?");
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                	if(num == 0){
                		urlBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                		num = 1;
                	}else{
                		urlBuilder.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                	}
                } catch (Exception e) {
                    urlBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
            num = 0;
        }
        return urlBuilder.toString();
    }

    
}

HttpClient:

jar包下載:

https://download.csdn.net/download/qq_43560721/12509637

package com.ece.manager.web.entranceGuardHK.util;

public class HttpClientResult {
	/**
	 * 響應狀態碼
	 */
	private int code;

	/**
	 * 響應數據
	 */
	private String content;

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
	

}
package com.ece.manager.web.entranceGuardHK.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
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;

/**
 * Description: httpClient工具類
 * 
 * @author JourWon
 * @date Created on 2018年4月19日
 */
public class HttpClientUtils {

	// 編碼格式。發送編碼格式統一用UTF-8
	private static final String ENCODING = "UTF-8";
	
	// 設置連接超時時間,單位毫秒。
	private static final int CONNECT_TIMEOUT = 6000;
	
	// 請求獲取數據的超時時間(即響應時間),單位毫秒。
	private static final int SOCKET_TIMEOUT = 6000;

	/**
	 * 發送get請求;不帶請求頭和請求參數
	 * 
	 * @param url 請求地址
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doGet(String url) throws Exception {
		return doGet(url, null, null);
	}
	
	/**
	 * 發送get請求;帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 請求參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
		return doGet(url, null, params);
	}

	/**
	 * 發送get請求;帶請求頭和請求參數
	 * 
	 * @param url 請求地址
	 * @param headers 請求頭集合
	 * @param params 請求參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
		// 創建httpClient對象
		CloseableHttpClient httpClient = HttpClients.createDefault();

		// 創建訪問的地址
		URIBuilder uriBuilder = new URIBuilder(url);
		if (params != null) {
			Set<Entry<String, String>> entrySet = params.entrySet();
			for (Entry<String, String> entry : entrySet) {
				uriBuilder.setParameter(entry.getKey(), entry.getValue());
			}
		}

		// 創建http對象
		HttpGet httpGet = new HttpGet(uriBuilder.build());
		/**
		 * setConnectTimeout:設置連接超時時間,單位毫秒。
		 * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
		 * 超時時間,單位毫秒。這個屬性是新加的屬性,因爲目前版本是可以共享連接池的。
		 * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
		 */
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
		httpGet.setConfig(requestConfig);
		
		// 設置請求頭
		packageHeader(headers, httpGet);

		// 創建httpResponse對象
		CloseableHttpResponse httpResponse = null;

		try {
			// 執行請求並獲得響應結果
			return getHttpClientResult(httpResponse, httpClient, httpGet);
		} finally {
			// 釋放資源
			release(httpResponse, httpClient);
		}
	}

	/**
	 * 發送post請求;不帶請求頭和請求參數
	 * 
	 * @param url 請求地址
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doPost(String url) throws Exception {
		return doPost(url, null, null);
	}
	
	/**
	 * 發送post請求;帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
		return doPost(url, null, params);
	}

	/**
	 * 發送post請求;帶請求頭和請求參數
	 * 
	 * @param url 請求地址
	 * @param headers 請求頭集合
	 * @param params 請求參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
		// 創建httpClient對象
		CloseableHttpClient httpClient = HttpClients.createDefault();

		// 創建http對象
		HttpPost httpPost = new HttpPost(url);
		/**
		 * setConnectTimeout:設置連接超時時間,單位毫秒。
		 * setConnectionRequestTimeout:設置從connect Manager(連接池)獲取Connection
		 * 超時時間,單位毫秒。這個屬性是新加的屬性,因爲目前版本是可以共享連接池的。
		 * setSocketTimeout:請求獲取數據的超時時間(即響應時間),單位毫秒。 如果訪問一個接口,多少時間內無法返回數據,就直接放棄此次調用。
		 */
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		// 設置請求頭
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
		packageHeader(headers, httpPost);
		
		// 封裝請求參數
		packageParam(params, httpPost);

		// 創建httpResponse對象
		CloseableHttpResponse httpResponse = null;

		try {
			// 執行請求並獲得響應結果
			return getHttpClientResult(httpResponse, httpClient, httpPost);
		} finally {
			// 釋放資源
			release(httpResponse, httpClient);
		}
	}

	/**
	 * 發送put請求;不帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doPut(String url) throws Exception {
		return doPut(url);
	}

	/**
	 * 發送put請求;帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
		httpPut.setConfig(requestConfig);
		
		packageParam(params, httpPut);

		CloseableHttpResponse httpResponse = null;

		try {
			return getHttpClientResult(httpResponse, httpClient, httpPut);
		} finally {
			release(httpResponse, httpClient);
		}
	}

	/**
	 * 發送delete請求;不帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doDelete(String url) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpDelete httpDelete = new HttpDelete(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
		httpDelete.setConfig(requestConfig);

		CloseableHttpResponse httpResponse = null;
		try {
			return getHttpClientResult(httpResponse, httpClient, httpDelete);
		} finally {
			release(httpResponse, httpClient);
		}
	}

	/**
	 * 發送delete請求;帶請求參數
	 * 
	 * @param url 請求地址
	 * @param params 參數集合
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
		if (params == null) {
			params = new HashMap<String, String>();
		}

		params.put("_method", "delete");
		return doPost(url, params);
	}
	
	/**
	 * Description: 封裝請求頭
	 * @param params
	 * @param httpMethod
	 */
	public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
		// 封裝請求頭
		if (params != null) {
			Set<Entry<String, String>> entrySet = params.entrySet();
			for (Entry<String, String> entry : entrySet) {
				// 設置到請求頭到HttpRequestBase對象中
				httpMethod.setHeader(entry.getKey(), entry.getValue());
			}
		}
	}

	/**
	 * Description: 封裝請求參數
	 * 
	 * @param params
	 * @param httpMethod
	 * @throws UnsupportedEncodingException
	 */
	public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
			throws UnsupportedEncodingException {
		// 封裝請求參數
		if (params != null) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			Set<Entry<String, String>> entrySet = params.entrySet();
			for (Entry<String, String> entry : entrySet) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}

			// 設置到請求的http對象中
			httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
		}
	}

	/**
	 * Description: 獲得響應結果
	 * 
	 * @param httpResponse
	 * @param httpClient
	 * @param httpMethod
	 * @return
	 * @throws Exception
	 */
	public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
			CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
		HttpClientResult http = new HttpClientResult();
		// 執行請求
		httpResponse = httpClient.execute(httpMethod);
		String content = "";
		// 獲取返回結果
		if (httpResponse != null && httpResponse.getStatusLine() != null) {
			
			if (httpResponse.getEntity() != null) {
				content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
			}
			http.setCode(httpResponse.getStatusLine().getStatusCode());
			http.setContent(content);
			return http;
		}
		http.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
		http.setContent(content);
		return http;
	}

	/**
	 * Description: 釋放資源
	 * 
	 * @param httpResponse
	 * @param httpClient
	 * @throws IOException
	 */
	public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
		// 釋放資源
		if (httpResponse != null) {
			httpResponse.close();
		}
		if (httpClient != null) {
			httpClient.close();
		}
	}

}

HttpRequest:

依賴:

<dependency>
	    <groupId>cn.hutool</groupId>
	    <artifactId>hutool-all</artifactId>
	    <version>5.3.5</version>
	</dependency>
 /**
     * 方法1:請求爲map
     *
     * @param url     下行接口地址
     * @param jsonStr 參數
     * @return 返回爲字符串
     */
public static String reqPostByMap(String url, Map<String, Object> params) {
    	System.out.println("------請求參數-----:\r\n"+params.toString());
        String resultStr =
                HttpRequest.post(url)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(JSONObject.toJSONString(params))
                        .execute().body();
        System.out.println("------響應參數-----:\r\n" + resultStr);
        return resultStr;
    }

    /**
     * 方法2:請求和返回均爲json字符串 純json處理
     *
     * @param url     下行接口地址
     * @param jsonStr 參數
     * @return 返回爲字符串
     */
    public static String reqPostByStr(String url, String jsonStr) {
        System.out.println("------請求參數-----:\r\n"+jsonStr);
    	String resultStr =
                HttpRequest.post(url)
                        .header("Accept", "application/json")
                        .header("Content-Type", "application/json;charset=utf-8")
                        .header("Authorization", auth)
                        .body(jsonStr)
                        .execute().body();
        System.out.println("------響應參數-----:\r\n" + resultStr);
        return resultStr;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章