精华内容
下载资源
问答
  • java请求第三方接口

    2018-12-11 16:38:53
    部署到客户服务器时遇到这个问题,请求第三方接口的方法没用了

    发送的commString可以是xml、json等格式的字符串

    	private  final org.apache.log4j.Logger Log = org.apache.log4j.Logger.getLogger(Translate.class);
     	public  String connectURL(String dest_url, String commString) {
            String rec_string = "";
            URL url = null;
            HttpURLConnection urlconn = null;
            OutputStream out = null;
            BufferedReader rd = null;
            try {
                url = new URL(dest_url);
                urlconn = (HttpURLConnection) url.openConnection();
                urlconn.setReadTimeout(1000 * 30);
                //urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");
                urlconn.setRequestMethod("POST");
                urlconn.setDoInput(true);
                urlconn.setDoOutput(true);
                out = urlconn.getOutputStream();
                out.write(commString.getBytes("UTF-8"));
                out.flush();
                out.close();
                rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                int ch;
                while ((ch = rd.read()) > -1)
                    sb.append((char) ch);
                rec_string = sb.toString();
            } catch (Exception e) {
                Log.error(e, e);
                return "";
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (urlconn != null) {
                        urlconn.disconnect();
                    }
                    if (rd != null) {
                        rd.close();
                    }
                } catch (Exception e) {
                    Log.error(e, e);
                }
            }
            // rec_string 为接口返回结果,可能是string类型的xml,json等,根据需求解析即可
            return rec_string;
        }
    

    注:如果你的war包请求第三方接口失败了,不妨试试这个方法

    展开全文
  • 文章目录第三方接口请求XML封装请求参数发送请求第三方接口响应XML解析第三方接口返回的XML数据工具类(sendMsgXml,getNodeValue) 第三方接口请求XML <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV...


    第三方接口请求XML

    <?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.example.org/Ec/">
    	<SOAP-ENV:Body>
    		<ns1:callService>			
    			<paramsJson>{json}</paramsJson>
    			<appToken>appToken</appToken>
    			<appKey>appKey</appKey>
    			<service>{service}</service>
    		</ns1:callService>
    	</SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    

    封装请求参数

    根据第三方接口提示进行拼接xml参数。

    	/**
         * 获取请求的json的参数
         *
         * @param shipmentTmsDTO
         * @return String
         */
        private String getJsonShipmentTmsDTO(ShipmentTmsDTO shipmentTmsDTO) {
            String jsonShipmentTmsDTO = JsonTools.objectToJson(shipmentTmsDTO);
            String jsonShipmentTmsDtoParam = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://www.example.org/Ec/\">" +
                    "<SOAP-ENV:Body>" +
                    "<ns1:callService>" +
                    "<paramsJson>" +
                    jsonShipmentTmsDTO +
                    "</paramsJson>" +
                    "<appToken>******</appToken>" +
                    "<appKey>******</appKey>" +
                    "<service>createOrder</service> " +
                    "</ns1:callService>" +
                    "</SOAP-ENV:Body>" +
                    "</SOAP-ENV:Envelope>";
            return jsonShipmentTmsDtoParam;
        }
    

    发送请求

    String shipmentTmsDtoString = getJsonShipmentTmsDTO(shipmentTmsDTO);
    String returnMsg = HttpsUtils.sendMsgXml(PUSH_SHIPMENT_TO_TMS_URL, shipmentTmsDtoString);
    

    PUSH_SHIPMENT_TO_TMS_URL 为推送的第三方接口URL

    第三方接口响应XML

    <?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.example.org/Ec/">
    	<SOAP-ENV:Body>
    		<ns1:callServiceResponse>			
    		<response>{json}</response>
    		</ns1:callServiceResponse>
    	</SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    

    解析第三方接口返回的XML数据

    通过节点获取XML中的json数据

    // String ————》XML
    Document doc = XmlUtil.StringTOXml(returnMsg);
    String nodePath = "/Envelope/Body/callServiceResponse/response";
    // getNodeValue
    String nodeValue = XmlUtil.getNodeValue(doc, nodePath);
    

    工具类(sendMsgXml,getNodeValue)

    	/**
         *
         * @param urlStr  接口地址
         * @param xmlInfo   xml格式参数数据
         * @return
         */
        public static String sendMsgXml(String urlStr, String xmlInfo) {
            StringBuffer buffer = new StringBuffer();
            try {
                URL url = new URL(urlStr);
                URLConnection con = url.openConnection();
                con.setDoOutput(true);
                OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "utf-8");
                out.write(xmlInfo);
                out.flush();
                out.close();
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String line = "";
                for (line = br.readLine(); line != null; line = br.readLine()) {
                    buffer.append(line);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return buffer+"";
        }
        
    	/**
         *
         * @param document
         * @return 某个节点的值 前提是需要知道xml格式,知道需要取的节点相对根节点所在位置
         */
        public static String getNodeValue(Document document, String nodePaht) {
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath path = xpfactory.newXPath();
            String servInitrBrch = "";
            try {
                servInitrBrch = path.evaluate(nodePaht, document);
            } catch (XPathExpressionException e) {
                e.printStackTrace();
            }
            return servInitrBrch;
        }
    
    展开全文
  • java请求第三方接口遇到的跨域问题

    千次阅读 2017-07-02 10:19:13
    自己项目中遇到的请求第三方接口跨域的问题: 首先项目中引入解决跨域的三个公共包; 包1: package com.jeeplus.modules.zzybaseservice; public class CyzHttpResponse {  protected String responseText;...

    自己项目中遇到的请求第三方接口跨域的问题:

    首先项目中引入解决跨域的三个公共包;

    包1:

    package com.jeeplus.modules.zzybaseservice;

    public class CyzHttpResponse {
        protected String responseText;  
        protected String session;       

        public String getResponseText() {
            return responseText;
        }

        public void setResponseText(String responseText) {
            this.responseText = responseText;
        }

        public String getSession() {
            return session;
        }

        public void setSession(String session) {
            this.session = session;
        }
    }

    包2:


    package com.jeeplus.modules.zzybaseservice;


    import java.io.BufferedReader;
    import java.io.Closeable;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;




    public class CyzHttpUtils {
        public static final String POST = "POST";
        public static final String GET = "GET";


        public static CyzHttpResponse doHttpPostJson(String strURL, String json, String session) {
            return doHttpPost(strURL, true, json, session);
        }
        public static CyzHttpResponse doHttpGetJson(String strURL, String json, String session) {
            return doHttpGet(strURL, true, json, session);
        }
        public static CyzHttpResponse doHttpPost(String strURL, String param, String session) {
            return doHttpPost(strURL, false, param, session);
        }


        private static CyzHttpResponse doHttpPost(String strURL, boolean jsonParam, String param, String session) {
            DataOutputStream out = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(strURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestMethod(POST); 
                connection.setRequestProperty("Accept", "*/*"); 
                connection.setRequestProperty("Connection", "keep-alive");
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
                if(jsonParam) {
                    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //JSON锟斤拷式锟斤拷锟斤拷
                }
                else {
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //锟斤拷�?�锟斤拷式锟斤拷锟斤�?
                }
                if(session != null) {
                    connection.setRequestProperty("Cookie", session);
                }
                connection.connect();


                if(param != null) {
                    out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes(param); 
                    out.flush();
                    out.close();
                }


                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }


                String sessionText = connection.getHeaderField("Set-Cookie"); 
                connection.disconnect(); 


                CyzHttpResponse httpResponse = new CyzHttpResponse();
                httpResponse.setResponseText(builder.toString());
                httpResponse.setSession(sessionText);
                return httpResponse;
            }
            catch (Exception e) {
                System.out.println("HTTP POST发生异常" + e.getLocalizedMessage());
            }
            finally {
                close(out); 
                close(reader); 
            }


            return null;
        }
        private static CyzHttpResponse doHttpGet(String strURL, boolean jsonParam, String param, String session) {
            DataOutputStream out = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(strURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestMethod(GET); 
                connection.setRequestProperty("Accept", "*/*"); 
                connection.setRequestProperty("Connection", "keep-alive");
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
                if(jsonParam) {
                    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); //JSON锟斤拷式锟斤拷锟斤拷
                }
                else {
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); //锟斤拷�?�锟斤拷式锟斤拷锟斤�?
                }
                if(session != null) {
                    connection.setRequestProperty("Cookie", session);
                }
                connection.connect();


                if(param != null) {
                    out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes(param); 
                    out.flush();
                    out.close();
                }


                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }


                String sessionText = connection.getHeaderField("Set-Cookie"); 
                connection.disconnect(); 


                CyzHttpResponse httpResponse = new CyzHttpResponse();
                httpResponse.setResponseText(builder.toString());
                httpResponse.setSession(sessionText);
                return httpResponse;
            }
            catch (Exception e) {
                System.out.println("HTTP POST发生异常" + e.getLocalizedMessage());
            }
            finally {
                close(out); 
                close(reader); 
            }


            return null;
        }
        public static void close(Closeable closeable) {
            if (closeable == null) {
                return;
            }


            try {
                closeable.close();
            }
            catch (Exception e) {
                System.out.println("发生异常" + e.getMessage());
                e.printStackTrace();
            }
        }
    }


    包3:

    package com.jeeplus.modules.zzybaseservice;




    import org.apache.commons.lang3.StringUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.google.gson.Gson;
    import com.jeeplus.common.web.BaseController;


    @Controller
    @RequestMapping(value = "${adminPath}/zzy/zzybase")
    public class ZzyBaseMesController extends BaseController {


    @RequestMapping(value = "/zzyService")
    @ResponseBody
    public String zzyService(HttpServletRequest request,HttpServletResponse response) {
    String ur=request.getParameter("url");
    if (StringUtils.isNotBlank(ur)) {
    CyzHttpResponse message = CyzHttpUtils.doHttpGetJson(ur, null, null);
    String mes = message.getResponseText();
    return renderString(response, mes);
    }else{
    return renderString(response, "path is error");
    }
    }
    }



    前台请求接口拿过来在后台处理跨域:(代码如下)

    @RequestMapping(value = "applicationOrderDo")
    @ResponseBody
    public String applicationOrderDo(HttpServletRequest request,HttpServletResponse response,Page page) {
    String url="http://smdt.canquick.com/hold/api/appointment.json";
    String office_id=request.getParameter("office_id");
    CyzHttpResponse message =CyzHttpUtils.doHttpGetJson(url+"?office_id="+office_id,null,null);//调用解决跨域问题(这里是get请求方式)
    String mes = message.getResponseText();
    Map map = (Map)JSON.parse(mes); 
    String date=((Object)map.get("data")).toString();
    List<Map<String,Object>> list=JsonToMap.FromJSONStringToList(date);
    /*String total=(String)list.get(0).get("total");
    page.setCount(Long.parseLong(total));
    System.out.println(page.getCount()+"");
    request.setAttribute("", total);*/
    //JSONObject mess = JSONObject.parseObject(mes);
    String json = JSON.toJSONString(list);
     
     
    return json;

    }


    展开全文
  • Map m=new HashMap();... // 接口返回信息 String sdkToken = new String(post.getResponseBody(), "UTF-8"); return sdkToken; } catch (Exception e) { e.printStackTrace(); } return R.ok(url); }
    @Override
    public R SDKtoken() {
      String url = "https://shunt-api.netless.link/v5/tokens/teams";
    Map m=new HashMap();
    m.put("accessKey",accessKey);
    m.put("secretAccessKey",secretAccessKey);
    m.put("lifespan",lifespan);
    m.put("role",role);
    JSONObject jsonObj=new JSONObject(m);
    String param=jsonObj.toString();
    String s=null;
    try {
        //创建连接
        HttpClient  httpclient = new HttpClient();
        PostMethod post = new PostMethod(url);
        // 设置编码方式
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        // 设置参数
        RequestEntity entity = new StringRequestEntity(param,"application/json","UTF-8");
        post.setRequestEntity(entity);
        // 执行请求
        httpclient.executeMethod(post);
        // 接口返回信息
        String sdkToken = new String(post.getResponseBody(), "UTF-8");
        return  sdkToken;
    } catch (Exception e) {
        e.printStackTrace();
    }
    
        return R.ok(url);
    }
    展开全文
  • //发送post请求 HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); httpPost.addHeader("token", sdkToken); //token RequestConfig requestConfig ...
  • public classHttpRequest {private static boolean debug = ...//get请求public staticString sendGet(String url, String param) {if (!debug) {return "";}String result= "";BufferedReader in= null;try{String ...
  • 知识点:java后台网络请求第三方接口代码实现(SSM)-- 获取requset请求过来的所有参数 package com.controller; import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;...
  • 对接第三方接口–使用post请求发送json数据实习4个多月,终于转正!终于可以安心好好上班,好好学习!第一篇播客记录下工作中的中的小知识点。本文记录的内容如下:1.使用HttpClient相关类,包括PostMethod,Request...
  • public classHttpRequest {private static boolean debug = ...//get请求public staticString sendGet(String url, String param) {if (!debug) {return "";}String result= "";BufferedReader in= null;try{String ...
  •   最近在写使用java后端去请求第三方接口的代码,给大家分享关于HttpEntity类的处理方式,而处理请求是需要根据第三方的要求来处理的,所以这里着重展示HttpEntity的处理。   在开始代码前,需要知晓几个前提: ...
  • java接收远程调用的数据,得到的是如上个数的返回内容,我怎么写才能获取到值,现在使用的请求方法如下:public static HttpResult postJsonData(String url, Map params, String charset) throws Exception{...
  • 采用get的方式不带参数 ... //1、创建请求方式对象 HttpGet get=new HttpGet(url); //2、创建客户端对象 HttpClient client= HttpClientBuilder.create().build(); try { //3、获取请求结果 HttpResp.
  • java请求第三方接口 直接使用jar包,不需要再一次造轮子 /** 需要导入的jar包 net.dongliu requests 4.18.1 */ package com.utils.httputil; import com.alibaba.fastjson.JSON; import ...
  • package ...import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import j...
  • 首先我们会得到第三方公司的接口文档,我们会依据其中的规范去做请求的参数或者获取加密手段 2.代码实践 需求 package com.seeyon.apps.hd.controller; import java.io.BufferedReader; import java.io....
  • import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; im.....
  • package ... import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; ...
  • http请求调用第三方接口获取token前言话不多说直接上代码测试 前言 最近在做项目对接,因为要频繁调用第三方的接口,所以就整理了一下代码,如有不足之处请指出! 话不多说直接上代码 public static String ...
  • 关于调用第三方接口开发里 // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); post的连接方式里上面两行代码是否必要存疑。看了网上的相关接口方法里,很少涉及到这个。所以下面几...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 655
精华内容 262
关键字:

java请求第三方接口

java 订阅