java發(fā)起http請求調用post與get接口的方法實例
一、java調用post接口
1、使用URLConnection或者HttpURLConnection
java自帶的,無需下載其他jar包
URLConnection方式調用,如果接口響應碼被服務端修改則無法接收到返回報文,只能當響應碼正確時才能接收到返回
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();
// 設置通用的請求屬性
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請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 發(fā)送請求參數(shù)
out.write(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
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塊來關閉輸出流、輸入流
finally{
if(out!=null){ try { out.close(); }catch(Exception ex){} }
if(in!=null){ try { in.close(); }catch(Exception ex){} }
}
return result.toString();
}
HttpURLConnection方式調用
//ms超時毫秒,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("接口響應碼:"+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個中的jar包。
詳情可以查看阿里云總線CSB
https://help.aliyun.com/document_detail/148571.html
public static String sendPost(){
String result = "";
HttpParameters.Builder builder = HttpParameters.newBuilder();
builder.requestURL("URL") // 設置請求的URL
.api("api") // 設置服務名
.version("version") // 設置版本號
.method("post") // 設置調用方式, get/post
.accessKey("ak").secretKey("sk"); // 設置accessKey 和 設置secretKey
// 設置請求參數(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調用get接口
使用java自帶的URLConnection
//將map型轉為請求參數(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();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
// 定義 BufferedReader輸入流來讀取URL的響應
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();
}
總結
到此這篇關于java發(fā)起http請求調用post與get接口的文章就介紹到這了,更多相關java調用post與get接口內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
spring-cloud入門之spring-cloud-config(配置中心)
這篇文章主要介紹了spring-cloud入門之spring-cloud-config(配置中心),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
詳解SpringCloud Gateway之過濾器GatewayFilter
這篇文章主要介紹了詳解SpringCloud Gateway之過濾器GatewayFilter,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
圖解Java經(jīng)典算法插入排序的原理與實現(xiàn)
插入排序的算法描述是一種簡單直觀的排序算法。其原理是通過構建有序序列,對于未排序數(shù)據(jù),在已排序序列中從后向前掃描,找到相應位置并插入。本文將用Java語言實現(xiàn)插入排序算法并進行可視化,感興趣的可以了解一下2022-09-09
java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別
這篇文章主要介紹了java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
MyBatis中一對多的xml配置方式(嵌套查詢/嵌套結果)
這篇文章主要介紹了MyBatis中一對多的xml配置方式(嵌套查詢/嵌套結果),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

