java發(fā)起http請(qǐng)求調(diào)用post與get接口的方法實(shí)例
一、java調(diào)用post接口
1、使用URLConnection或者HttpURLConnection
java自帶的,無(wú)需下載其他jar包
URLConnection方式調(diào)用,如果接口響應(yīng)碼被服務(wù)端修改則無(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è)置通用的請(qǐng)求屬性 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請(qǐng)求必須設(shè)置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流 out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 發(fā)送請(qǐng)求參數(shù) out.write(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來(lái)讀取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 請(qǐng)求出現(xiàn)異常!"+e); e.printStackTrace(); } //使用finally塊來(lái)關(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è)置請(qǐng)求的URL .api("api") // 設(shè)置服務(wù)名 .version("version") // 設(shè)置版本號(hào) .method("post") // 設(shè)置調(diào)用方式, get/post .accessKey("ak").secretKey("sk"); // 設(shè)置accessKey 和 設(shè)置secretKey // 設(shè)置請(qǐng)求參數(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)為請(qǐng)求參數(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è)置通用的請(qǐng)求屬性 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輸入流來(lái)讀取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請(qǐng)求出現(xiàn)異常!" + e); e.printStackTrace(); } finally { if (in != null){ try { in.close(); }catch(Exception e2){} } } return result.toString(); }
總結(jié)
到此這篇關(guān)于java發(fā)起http請(qǐng)求調(diào)用post與get接口的文章就介紹到這了,更多相關(guān)java調(diào)用post與get接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java設(shè)計(jì)模式中的簡(jiǎn)單工廠模式解析
這篇文章主要介紹了Java設(shè)計(jì)模式中的簡(jiǎn)單工廠模式解析,簡(jiǎn)單工廠模式提供一個(gè)創(chuàng)建對(duì)象實(shí)例的功能,而無(wú)須關(guān)心其具體實(shí)現(xiàn),被創(chuàng)建實(shí)例的類型可以是接口、抽象類,也可以是具體的類,需要的朋友可以參考下2023-11-11spring-cloud入門之spring-cloud-config(配置中心)
這篇文章主要介紹了spring-cloud入門之spring-cloud-config(配置中心),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-01-01詳解SpringCloud Gateway之過濾器GatewayFilter
這篇文章主要介紹了詳解SpringCloud Gateway之過濾器GatewayFilter,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-10-10圖解Java經(jīng)典算法插入排序的原理與實(shí)現(xiàn)
插入排序的算法描述是一種簡(jiǎn)單直觀的排序算法。其原理是通過構(gòu)建有序序列,對(duì)于未排序數(shù)據(jù),在已排序序列中從后向前掃描,找到相應(yīng)位置并插入。本文將用Java語(yǔ)言實(shí)現(xiàn)插入排序算法并進(jìn)行可視化,感興趣的可以了解一下2022-09-09java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別
這篇文章主要介紹了java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04MyBatis中一對(duì)多的xml配置方式(嵌套查詢/嵌套結(jié)果)
這篇文章主要介紹了MyBatis中一對(duì)多的xml配置方式(嵌套查詢/嵌套結(jié)果),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03