java發(fā)起http請(qǐng)求調(diào)用post與get接口的方法實(shí)例
一、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è)置通用的請(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輸入流來讀取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塊來關(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輸入流來讀取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)文章
crawler4j抓取頁面使用jsoup解析html時(shí)的解決方法
crawler4j對(duì)response沒有指定編碼的頁面,解析成亂碼,很讓人煩惱,下面給出解決方法,需要的朋友可以參考下2014-04-04
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)算符,結(jié)合實(shí)例形式詳細(xì)分析了java基本數(shù)據(jù)類型、數(shù)據(jù)類型轉(zhuǎn)換、算術(shù)運(yùn)算符、邏輯運(yùn)算符等相關(guān)原理與操作技巧,需要的朋友可以參考下2020-02-02
Mybatis注解方式操作Oracle數(shù)據(jù)庫(kù)詳解
這篇文章主要介紹了Mybatis注解方式操作Oracle數(shù)據(jù)庫(kù)詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Spring Data Jpa實(shí)現(xiàn)自定義repository轉(zhuǎn)DTO
這篇文章主要介紹了Spring Data Jpa實(shí)現(xiàn)自定義repository轉(zhuǎn)DTO,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
springboot2版本無法加載靜態(tài)資源問題解決
這篇文章主要介紹了springboot2版本無法加載靜態(tài)資源問題解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(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)行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01

