Java?webservice的POST和GET請(qǐng)求調(diào)用方式
webservice的POST和GET請(qǐng)求調(diào)用
POST請(qǐng)求
1.發(fā)送請(qǐng)求
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.google.common.io.ByteStreams;
/**
?* HttpClient發(fā)送SOAP請(qǐng)求
?* @param wsdl url地址
?* @param xml ? 請(qǐng)求體參數(shù)
?* @return
?* @throws Exception
?*/
public static String sendHttpPost(String wsdl, String xml) throws Exception{
? ? int timeout = 10000;
? ? // HttpClient發(fā)送SOAP請(qǐng)求
? ? System.out.println("HttpClient 發(fā)送SOAP請(qǐng)求");
? ? HttpClient client = new HttpClient();
? ? PostMethod postMethod = new PostMethod(wsdl);
? ? // 設(shè)置連接超時(shí)
? ? client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
? ? // 設(shè)置讀取時(shí)間超時(shí)
? ? client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
? ? // 然后把Soap請(qǐng)求數(shù)據(jù)添加到PostMethod中
? ? RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml", "UTF-8");
? ? // 設(shè)置請(qǐng)求體
? ? postMethod.setRequestEntity(requestEntity);
? ? int status = client.executeMethod(postMethod);
? ? // 打印請(qǐng)求狀態(tài)碼
? ? System.out.println("status:" + status);
? ? // 獲取響應(yīng)體輸入流
? ? InputStream is = postMethod.getResponseBodyAsStream();
? ? // 獲取請(qǐng)求結(jié)果字符串
? ? return new String(ByteStreams.toByteArray(is));
}
/**
?* HttpURLConnection 發(fā)送SOAP請(qǐng)求
?* @param wsdl url地址
?* @param xml ? 請(qǐng)求體參數(shù)
?* @return
?* @throws Exception
?*/
public static String sendURLConnection(String wsdl, String xml) throws Exception{
? ? int timeout = 10000;
? ? // HttpURLConnection 發(fā)送SOAP請(qǐng)求
? ? System.out.println("HttpURLConnection 發(fā)送SOAP請(qǐng)求");
? ? URL url = new URL(wsdl);
? ? HttpURLConnection conn = (HttpURLConnection) url.openConnection();
? ? conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
? ? conn.setRequestMethod("POST");
? ? conn.setUseCaches(false);
? ? conn.setDoInput(true);
? ? conn.setDoOutput(true);
? ? conn.setConnectTimeout(timeout);
? ? conn.setReadTimeout(timeout);
? ? DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
? ? dos.write(xml.getBytes("utf-8"));
? ? dos.flush();
? ? InputStream inputStream = conn.getInputStream();
? ? // 獲取請(qǐng)求結(jié)果字符串
? ? return new String(ByteStreams.toByteArray(inputStream));
}ByteStreams的maven
<dependency> ? ? ? ? <groupId>com.google.guava</groupId> ? ? ? ? <artifactId>guava</artifactId> ? ? ? ? <version>27.0.1-jre</version> ? ? </dependency>
2.POST請(qǐng)求體
/**
?* POST請(qǐng)求體
?* @param map 請(qǐng)求參數(shù)
?* @param methodName 方法名
?* @return
?*/
public static String getXml(Map<String ,String> map , String methodName){
? ? StringBuffer sb = new StringBuffer("");
? ? sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
? ? sb.append("<soap:Envelope "
? ? ? ? ? ? + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
? ? ? ? ? ? + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
? ? ? ? ? ? + "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
? ? sb.append("<soap:Body>");
? ? sb.append("<" + methodName + " xmlns='http://tempuri.org/'>");
? ? //post參數(shù)
? ? for (String str : map.keySet()){
? ? ? ? sb.append("<"+str+">"+map.get(str)+"</"+str+">");
? ? }
? ? sb.append("</" + methodName + ">");
? ? sb.append("</soap:Body>");
? ? sb.append("</soap:Envelope>");
? ? return sb.toString();
}3.測(cè)試
/**
* HTTP POST請(qǐng)求
*/
public static void main(String[] args) throws Exception{
? ? String wsdl = "http://IP:端口/xxx?wsdl";
? ? String methodName = "方法名";
? ? Map<String ,String> map = new HashMap<>();
? ? map.put("參數(shù)名","參數(shù)值");
? ? //請(qǐng)求體xml
? ? String xml = getXml(map, methodName);
? ? //發(fā)送請(qǐng)求
? ? String s = sendHttpPost(wsdl, xml);
? ? System.out.println(s);
}GET請(qǐng)求
/**
* 發(fā)送請(qǐng)求
*/
import com.google.common.io.ByteStreams;
import org.apache.commons.httpclient.HttpStatus;
import org.codehaus.jettison.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public static void main(String[] args) throws Exception{
?? ?String url = "http://IP:端口/xxx/方法名?參數(shù)名=參數(shù)值";
? ? Map result = new HashMap(16);
? ? try {
? ? ? ? URL url = new URL(url);
? ? ? ? HttpURLConnection connection = (HttpURLConnection)url.openConnection();
? ? ? ? //設(shè)置輸入輸出,因?yàn)槟J(rèn)新創(chuàng)建的connection沒(méi)有讀寫(xiě)權(quán)限,
? ? ? ? connection.setDoInput(true);
? ? ? ? connection.setDoOutput(true);
? ? ? ? //接收服務(wù)端響應(yīng)
? ? ? ? int responseCode = connection.getResponseCode();
? ? ? ? if(HttpStatus.SC_OK == responseCode){//表示服務(wù)端響應(yīng)成功
? ? ? ? ? ? InputStream is = connection.getInputStream();
? ? ? ? ? ? //響應(yīng)結(jié)果
? ? ? ? ? ? String s = new String(ByteStreams.toByteArray(is));
? ? ? ? ? ? result = com.alibaba.fastjson.JSONObject.parseObject(s, Map.class);
? ? ? ? }
? ? } catch (Exception e) {
? ? ? ? e.printStackTrace();
? ? ? ? System.out.println("查詢(xún)?cè)诰€狀態(tài)1:"+e.getMessage());
? ? }
? ? System.out.println(result);
}通過(guò)webService調(diào)第三方提供的接口post與get
需求:第三方提供接口路徑,在自己的項(xiàng)目中進(jìn)行調(diào)用
注意點(diǎn):調(diào)不通的時(shí)候排除接口本身的問(wèn)題后,看看自己調(diào)用路徑是不是正確的,有沒(méi)多了或者少了【/】,參數(shù)的格式是不是跟接口文檔的一致,再不行,那有可能是編碼或者流處理的問(wèn)題,我在實(shí)際開(kāi)發(fā)中就是因?yàn)榱魈幚淼膯?wèn)題導(dǎo)致調(diào)不通。
POST
? ? public static String post(String method,String urls,String params){
? ? ? ? OutputStreamWriter out = null;
? ? ? ? try
? ? ? ? {
? ? ? ? ? ? URL url = new URL(urls);//第三方接口路徑
? ? ? ? ? ? HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
? ? ? ? ? ? // 創(chuàng)建連接
? ? ? ? ? ? conn.setDoOutput(true);
? ? ? ? ? ? conn.setDoInput(true);
? ? ? ? ? ? conn.setUseCaches(false);
? ? ? ? ? ? conn.setRequestMethod(method);//請(qǐng)求方式 此處為POST
? ? ? ? ? ? String token= "123456789";//根據(jù)實(shí)際項(xiàng)目需要,可能需要token值
? ? ? ? ? ? conn.setRequestProperty("token", token);
? ? ? ? ? ? conn.setRequestProperty("Content-type", "application/json");
? ? ? ? ? ? conn.connect();
? ? ? ? ? ? out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//編碼設(shè)置
? ? ? ? ? ? out.write(params);
? ? ? ? ? ? out.flush();
? ? ? ? ? ? out.close();
? ? ? ? ? ? // 獲取響應(yīng)
? ? ? ? ? ? BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()));
? ? ? ? ? ? String lines;
? ? ? ? ? ? StringBuffer sb = new StringBuffer();
? ? ? ? ? ? while ((lines = reader.readLine()) != null ){
? ? ? ? ? ? ? ? lines = new String(lines.getBytes(), "utf-8" );
? ? ? ? ? ? ? ? sb.append(lines);
? ? ? ? ? ? }
? ? ? ? ? ? reader.close();
? ? ? ? ? ? System.out.println(sb);
? ? ? ? ? ? return sb.toString(); ? ? ? ?
? ? ? ? }catch(Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return null;
? ? }GET
//根據(jù)各自需要返回?cái)?shù)組或者字符串 ??
//public static String getObject(String method,String urls,String params){
?public static JSONArray getArray(String method,String urls,String params){
? ? ? ? OutputStreamWriter out = null;
? ? ? ? try{
? ? ? ? ? ? URL url = new URL(urls);//接口路徑
? ? ? ? ? ? HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
? ? ? ? ? ? conn.setRequestMethod(method);//請(qǐng)求方法 此處為GET
? ? ? ? ? ? conn.setDoInput(true);
? ? ? ? ? ? conn.setDoOutput(true);
? ? ? ? ? ? String token = "123456789";//請(qǐng)求頭token
? ? ? ? ? ? conn.setRequestProperty("token",token);
? ? ? ? ? ? conn.connect();
? ? ? ? ? ? int status = conn.getResponseCode();
? ? ? ? ? ? System.out.println(status);
?
? ? ? ? ? ? if(status == 200){
? ? ? ? ? ? ? ? BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//怎么也調(diào)不通的時(shí)候,有可能流處理有問(wèn)題
? ? ? ? ? ? ? ? String str = "";
? ? ? ? ? ? ? ? StringBuffer sb = new StringBuffer();
? ? ? ? ? ? ? ? while((str=reader.readLine()) != null){
? ? ? ? ? ? ? ? ? ? sb.append(str);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //返回字符串的話,就直接返回 sb.toString()
? ? ? ? ? ? ? ? return JSONArray.parseArray(sb.toString());
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("請(qǐng)求服務(wù)失敗,錯(cuò)誤碼為"+status);
? ? ? ? }catch(Exception e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return null;
? ? }用實(shí)體類(lèi)進(jìn)行接收返回值的話,需要將返回?cái)?shù)據(jù)做下轉(zhuǎn)換,轉(zhuǎn)成我們需要的實(shí)體類(lèi)格式
//返回?cái)?shù)組轉(zhuǎn)實(shí)體類(lèi)
JSONArray sb = getArray(method,url,params);
if (sb!=null){
? ? List<實(shí)體類(lèi)> list = JSONObject.parseArray(sb.toJSONString(), 實(shí)體類(lèi).class);
? ? ?return list;
}else {
? ? ?throw new CustomException("調(diào)用接口失敗");
}
?
//返回字符串轉(zhuǎn)實(shí)體類(lèi)
String json = JSONObject.toJSONString(params);
String sb = post(method,url,json);
JSONObject testJson = JSONObject.parseObject(sb);
實(shí)體類(lèi)dto = JSON.toJavaObject(testJson,實(shí)體類(lèi).class);以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
(starters)springboot-starter整合阿里云datahub方式
這篇文章主要介紹了(starters)springboot-starter整合阿里云datahub方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Maven項(xiàng)目打包成可執(zhí)行Jar文件步驟解析
這篇文章主要介紹了Maven項(xiàng)目如何打包成可執(zhí)行Jar文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
spring mybatis多數(shù)據(jù)源實(shí)例詳解
本文主要介紹sping mybatis多數(shù)據(jù)源處理,在開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)遇到多個(gè)數(shù)據(jù)庫(kù),這里給大家舉例說(shuō)明如何處理,希望能幫助有需要的小伙伴2016-07-07
SpringBoot項(xiàng)目部署到騰訊云的實(shí)現(xiàn)步驟
本文主要介紹了SpringBoot項(xiàng)目部署到騰訊云的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
Mybatis-Plus實(shí)體類(lèi)繼承Model的使用小結(jié)
Mybatis-Plus實(shí)體類(lèi)繼承Model的使用是Mybatis-Plus中的一個(gè)重要特性,它允許開(kāi)發(fā)者通過(guò)繼承Model類(lèi)來(lái)快速實(shí)現(xiàn)一些通用的功能,本文主要介紹了Mybatis-Plus實(shí)體類(lèi)繼承Model的使用小結(jié),感興趣的可以了解一下2024-07-07
Mybatis攔截器注解@Intercepts與@Signature注解使用
本文主要介紹了Mybatis攔截器注解@Intercepts與@Signature注解使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07

