webservice的POST和GET请求调用
POST请求
1.发送请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
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发送SOAP请求 * @param wsdl url地址 * @param xml 请求体参数 * @return * @throws Exception */ public static String sendHttpPost(String wsdl, String xml) throws Exception{ int timeout = 10000 ; // HttpClient发送SOAP请求 System.out.println( "HttpClient 发送SOAP请求" ); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(wsdl); // 设置连接超时 client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); // 设置读取时间超时 client.getHttpConnectionManager().getParams().setSoTimeout(timeout); // 然后把Soap请求数据添加到PostMethod中 RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml" , "UTF-8" ); // 设置请求体 postMethod.setRequestEntity(requestEntity); int status = client.executeMethod(postMethod); // 打印请求状态码 System.out.println( "status:" + status); // 获取响应体输入流 InputStream is = postMethod.getResponseBodyAsStream(); // 获取请求结果字符串 return new String(ByteStreams.toByteArray(is)); } /** * HttpURLConnection 发送SOAP请求 * @param wsdl url地址 * @param xml 请求体参数 * @return * @throws Exception */ public static String sendURLConnection(String wsdl, String xml) throws Exception{ int timeout = 10000 ; // HttpURLConnection 发送SOAP请求 System.out.println( "HttpURLConnection 发送SOAP请求" ); 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(); // 获取请求结果字符串 return new String(ByteStreams.toByteArray(inputStream)); } |
ByteStreams的maven
1 2 3 4 5 |
< dependency > < groupId >com.google.guava</ groupId > < artifactId >guava</ artifactId > < version >27.0.1-jre</ version > </ dependency > |
2.POST请求体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** * POST请求体 * @param map 请求参数 * @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参数 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.测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * HTTP POST请求 */ public static void main(String[] args) throws Exception{ String wsdl = "http://IP:端口/xxx?wsdl" ; String methodName = "方法名" ; Map<String ,String> map = new HashMap<>(); map.put( "参数名" , "参数值" ); //请求体xml String xml = getXml(map, methodName); //发送请求 String s = sendHttpPost(wsdl, xml); System.out.println(s); } |
GET请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
/** * 发送请求 */ 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/方法名?参数名=参数值" ; Map result = new HashMap( 16 ); try { URL url = new URL(url); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); //设置输入输出,因为默认新创建的connection没有读写权限, connection.setDoInput( true ); connection.setDoOutput( true ); //接收服务端响应 int responseCode = connection.getResponseCode(); if (HttpStatus.SC_OK == responseCode){ //表示服务端响应成功 InputStream is = connection.getInputStream(); //响应结果 String s = new String(ByteStreams.toByteArray(is)); result = com.alibaba.fastjson.JSONObject.parseObject(s, Map. class ); } } catch (Exception e) { e.printStackTrace(); System.out.println( "查询在线状态1:" +e.getMessage()); } System.out.println(result); } |
通过webService调第三方提供的接口post与get
需求: 第三方提供接口路径,在自己的项目中进行调用
注意点: 调不通的时候排除接口本身的问题后,看看自己调用路径是不是正确的,有没多了或者少了【/】,参数的格式是不是跟接口文档的一致,再不行,那有可能是编码或者流处理的问题,我在实际开发中就是因为流处理的问题导致调不通。
POST
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public static String post(String method,String urls,String params){ OutputStreamWriter out = null ; try { URL url = new URL(urls); //第三方接口路径 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // 创建连接 conn.setDoOutput( true ); conn.setDoInput( true ); conn.setUseCaches( false ); conn.setRequestMethod(method); //请求方式 此处为POST String token= "123456789" ; //根据实际项目需要,可能需要token值 conn.setRequestProperty( "token" , token); conn.setRequestProperty( "Content-type" , "application/json" ); conn.connect(); out = new OutputStreamWriter(conn.getOutputStream(), "utf-8" ); //编码设置 out.write(params); out.flush(); out.close(); // 获取响应 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
//根据各自需要返回数组或者字符串 //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); //请求方法 此处为GET conn.setDoInput( true ); conn.setDoOutput( true ); String token = "123456789" ; //请求头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())); //怎么也调不通的时候,有可能流处理有问题 String str = "" ; StringBuffer sb = new StringBuffer(); while ((str=reader.readLine()) != null ){ sb.append(str); } //返回字符串的话,就直接返回 sb.toString() return JSONArray.parseArray(sb.toString()); } System.out.println( "请求服务失败,错误码为" +status); } catch (Exception e){ e.printStackTrace(); } return null ; } |
用实体类进行接收返回值的话,需要将返回数据做下转换,转成我们需要的实体类格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//返回数组转实体类 JSONArray sb = getArray(method,url,params); if (sb!= null ){ List<实体类> list = JSONObject.parseArray(sb.toJSONString(), 实体类. class ); return list; } else { throw new CustomException( "调用接口失败" ); }
//返回字符串转实体类 String json = JSONObject.toJSONString(params); String sb = post(method,url,json); JSONObject testJson = JSONObject.parseObject(sb); 实体类dto = JSON.toJavaObject(testJson,实体类. class ); |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/weixin_42393758/article/details/84383415
查看更多关于Java webservice的POST和GET请求调用方式的详细内容...