最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java發(fā)起http請求調(diào)用post與get接口的方法實(shí)例

 更新時(shí)間:2022年08月11日 09:22:16   作者:GAo_ei  
在實(shí)際開發(fā)過程中,我們經(jīng)常需要調(diào)用對方提供的接口或測試自己寫的接口是否合適,下面這篇文章主要給大家介紹了關(guān)于java發(fā)起http請求調(diào)用post與get接口的相關(guān)資料,需要的朋友可以參考下

一、java調(diào)用post接口

1、使用URLConnection或者HttpURLConnection

java自帶的,無需下載其他jar包

URLConnection方式調(diào)用,如果接口響應(yīng)碼被服務(wù)端修改則無法接收到返回報(bào)文,只能當(dāng)響應(yīng)碼正確時(shí)才能接收到返回

public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder("");
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            // 設(shè)置通用的請求屬性
            conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發(fā)送POST請求必須設(shè)置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應(yīng)的輸出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 發(fā)送請求參數(shù)
            out.write(param);
            // flush輸出流的緩沖
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應(yīng)
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("發(fā)送 POST 請求出現(xiàn)異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關(guān)閉輸出流、輸入流
        finally{
        	if(out!=null){ try { out.close(); }catch(Exception ex){} }
        	if(in!=null){ try { in.close(); }catch(Exception ex){} }
        }
        return result.toString();
    }

HttpURLConnection方式調(diào)用

//ms超時(shí)毫秒,url地址,json入?yún)?
public static String httpJson(int ms,String url,String json) throws Exception{
		String err = "00", line = null;
		StringBuilder sb = new StringBuilder();
		HttpURLConnection conn = null;
		BufferedWriter out = null;
		BufferedReader in = null;
		try{
			conn = (HttpURLConnection) (new URL(url.replaceAll("/","/"))).openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(ms);
			conn.setReadTimeout(ms);
			conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
			conn.connect();
			out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
			out.write(new String(json.getBytes(), "utf-8"));
			out.flush();//發(fā)送參數(shù)
			int code = conn.getResponseCode();
			if (conn.getResponseCode()==200){
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				while ((line=in.readLine())!=null)
					sb.append(line);
			}//接收返回值
			
		}catch(Exception ex){
			err=ex.getMessage();
		}
		try{ if (out!=null) out.close(); }catch(Exception ex){}; 
		try{ if (in!=null) in.close(); }catch(Exception ex){};
		try{ if (conn!=null) conn.disconnect();}catch(Exception ex){}
		if (!err.equals("00")) throw new Exception(err);
		return sb.toString();
	}

2、使用CloseableHttpClient

使用的jar包

<dependency>
    <groupId>com.alibaba.csb.sdk</groupId>
    <artifactId>http-client</artifactId>
    <version>1.1.5.1</version>
</dependency>
public static String httpPostJson(String url,String json) throws Exception{
		String data=""; 
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity se = new StringEntity(json,Charset.forName("UTF-8"));
	        se.setContentType("text/json");
	        se.setContentEncoding("UTF-8");
	        httppost.setEntity(se);
	        response = httpClient.execute(httppost);
	        int code = response.getStatusLine().getStatusCode();
	        System.out.println("接口響應(yīng)碼:"+code);
	        data = EntityUtils.toString(response.getEntity(), "utf-8");
	        EntityUtils.consume(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(response!=null){ try{response.close();}catch (IOException e){} }
			if(httpClient!=null){ try{httpClient.close();}catch(IOException e){} }
		}
		return data;
	}

3、使用HttpCaller

使用的jar包同第2個(gè)中的jar包。

詳情可以查看阿里云總線CSB

https://help.aliyun.com/document_detail/148571.html

public static String sendPost(){
		String result = "";
		HttpParameters.Builder builder = HttpParameters.newBuilder();
		builder.requestURL("URL") // 設(shè)置請求的URL
        		.api("api") // 設(shè)置服務(wù)名
        		.version("version") // 設(shè)置版本號
        		.method("post") // 設(shè)置調(diào)用方式, get/post
        		.accessKey("ak").secretKey("sk"); // 設(shè)置accessKey 和 設(shè)置secretKey
		// 設(shè)置請求參數(shù)(json格式)
        Map<String,String> param = new HashMap<String,String>();
        param.put("key1","value1");
        param.put("key2","value2");
        //加密,沒有加密則不需要encryptParam,直接用param
        Map<String,String> encryptParam = new HashMap<String,String>();
        encryptParam.put("key3", getData(JSON.toJSONString(param)));
        ContentBody cb = new ContentBody(JSON.toJSONString(encryptParam));
        builder.contentBody(cb);
        
        try {
        	result = HttpCaller.invoke(builder.build());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
        return result;
	}
	
	//自己的加密方式
	public static String getData(String data1){
		return "加密后的密文";
	}

二、java調(diào)用get接口

使用java自帶的URLConnection

//將map型轉(zhuǎn)為請求參數(shù)型
public static String getUrlData(Map<Object, Object> data) throws Exception{
	StringBuffer sb = new StringBuffer();
	try {
		Set<Map.Entry<Object, Object>> entries = data.entrySet();
		Iterator<Map.Entry<Object, Object>> iterators = entries.iterator();
		while(iterators.hasNext()){
			Map.Entry<Object, Object> next = iterators.next();
			sb.append(next.getKey().toString().trim()).append("=").append(URLEncoder.encode(next.getValue() + "", "UTF-8").trim()).append("&");
		}
		sb.deleteCharAt(sb.length() - 1);
	} catch (Exception e) {
		sb.append(e.toString());
	}
	return sb.toString();
}

//strUrl截止到?,例:http://127.0.0.1:8080/api/method?
public static String httpGet(String strUrl){
	Map<Object, Object> params = new HashMap<Object, Object>();
	params.put("key1", "value1");
	params.put("key2", "value2");
	String url=strUrl + getUrlData(params);
	
  	StringBuilder result = new StringBuilder();
    BufferedReader in = null;
    try {
        URL realUrl = new URL(url);
        // 打開和URL之間的連接
        URLConnection connection = realUrl.openConnection();
        // 設(shè)置通用的請求屬性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 建立實(shí)際的連接
        connection.connect();
        // 獲取所有響應(yīng)頭字段
        // 定義 BufferedReader輸入流來讀取URL的響應(yīng)
        in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {
        System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
        e.printStackTrace();
    }
    finally {
    	if (in != null){ try { in.close(); }catch(Exception e2){} }
    }
    return result.toString();
}

總結(jié)

到此這篇關(guān)于java發(fā)起http請求調(diào)用post與get接口的文章就介紹到這了,更多相關(guān)java調(diào)用post與get接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • crawler4j抓取頁面使用jsoup解析html時(shí)的解決方法

    crawler4j抓取頁面使用jsoup解析html時(shí)的解決方法

    crawler4j對response沒有指定編碼的頁面,解析成亂碼,很讓人煩惱,下面給出解決方法,需要的朋友可以參考下
    2014-04-04
  • Java中的幾種關(guān)鍵字的使用小結(jié)

    Java中的幾種關(guān)鍵字的使用小結(jié)

    本文主要介紹了Java中的幾種關(guān)鍵字的使用小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • IntelliJ IDEA中查看當(dāng)前類的所有繼承關(guān)系圖

    IntelliJ IDEA中查看當(dāng)前類的所有繼承關(guān)系圖

    今天小編就為大家分享一篇關(guān)于IntelliJ IDEA中查看當(dāng)前類的所有繼承關(guān)系圖,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Java基本數(shù)據(jù)類型和運(yùn)算符詳解

    Java基本數(shù)據(jù)類型和運(yùn)算符詳解

    這篇文章主要介紹了Java基本數(shù)據(jù)類型和運(yùn)算符,結(jié)合實(shí)例形式詳細(xì)分析了java基本數(shù)據(jù)類型、數(shù)據(jù)類型轉(zhuǎn)換、算術(shù)運(yùn)算符、邏輯運(yùn)算符等相關(guān)原理與操作技巧,需要的朋友可以參考下
    2020-02-02
  • Mybatis注解方式操作Oracle數(shù)據(jù)庫詳解

    Mybatis注解方式操作Oracle數(shù)據(jù)庫詳解

    這篇文章主要介紹了Mybatis注解方式操作Oracle數(shù)據(jù)庫詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • Windows部署Jar包的三種方式圖文詳解

    Windows部署Jar包的三種方式圖文詳解

    使用Java編寫了一些有用的工具,因?yàn)椴环奖悴渴鸬椒?wù)器上,所以需要把Java生成的jar包在本地Windows上部署,這篇文章主要給大家介紹了關(guān)于Windows部署Jar包的三種方式,需要的朋友可以參考下
    2023-07-07
  • Spring Cloud Stream異常處理過程解析

    Spring Cloud Stream異常處理過程解析

    這篇文章主要介紹了Spring Cloud Stream異常處理過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • Spring Data Jpa實(shí)現(xiàn)自定義repository轉(zhuǎn)DTO

    Spring Data Jpa實(shí)現(xiàn)自定義repository轉(zhuǎn)DTO

    這篇文章主要介紹了Spring Data Jpa實(shí)現(xiàn)自定義repository轉(zhuǎn)DTO,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • springboot2版本無法加載靜態(tài)資源問題解決

    springboot2版本無法加載靜態(tài)資源問題解決

    這篇文章主要介紹了springboot2版本無法加載靜態(tài)資源問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • spring boot項(xiàng)目沒有mainClass如何實(shí)現(xiàn)打包運(yùn)行

    spring boot項(xiàng)目沒有mainClass如何實(shí)現(xiàn)打包運(yùn)行

    這篇文章主要介紹了spring boot項(xiàng)目沒有mainClass如何實(shí)現(xiàn)打包運(yùn)行,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01

最新評論

巴林右旗| 阳城县| 驻马店市| 兖州市| 遵义县| 始兴县| 兴安盟| 曲阜市| 营山县| 菏泽市| 紫金县| 噶尔县| 海口市| 丘北县| 临沭县| 嵊州市| 大安市| 商洛市| 化州市| 繁峙县| 宁明县| 定安县| 巴彦县| 紫金县| 西青区| 盐亭县| 汝阳县| 茶陵县| 尼木县| 四川省| 北流市| 工布江达县| 辽阳市| 平武县| 潜山县| 晋宁县| 六枝特区| 新沂市| 五原县| 湟中县| 灵台县|