调用接口获取接口返回信息的几种工具方法

返回值为String类型

/**
     *
     * @param urlStr 接口地址
     * @param paras 请求参数
     * @param type  调接口传参类型
     * @return
     * @throws Exception
     */

public static String invokeFareInterface(String urlStr, String paras, String type) throws Exception{
        OutputStream os = null;
        StringBuffer buffer = null;
        InputStreamReader reader = null;
//        GZIPInputStream in = null;
        try {
            int c = 0;
            buffer = new StringBuffer();

            if(urlStr!=null && !"".equals(urlStr)){
                URL url = new URL(urlStr);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setReadTimeout(60000); // 15s超时
                con.setDoOutput(true);
                if(type!=null && "post".equals(type)){    
                    con.setRequestMethod("POST");
                    con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                }else{}
                os = con.getOutputStream();
                os.write(paras.getBytes());
                os.flush();
                os.close();
                //in = new GZIPInputStream(con.getInputStream());
                int code = con.getResponseCode();            
                if (code == 200) { // 返回成功
                    reader = new InputStreamReader(con.getInputStream(), "UTF-8");
                    while ((c = reader.read()) != -1) {
                        buffer.append((char) c);
                    }
                } else { // 访问失败
                    throw new Exception("Error occur when try to visit the url:" +
                            url.getPath() + " using HttpURLConnection");
                }
                url = null;
                con = null;
            }else{
                //exceptionlog.warn("Invoke 运价接口url为空");
            }
        } catch (Exception e) {
            //exceptionlog.error(this.getClass()+"invoke 运价接口异常:"+e.getMessage());
//            System.out.println(this.getClass()+"invoke 运价接口异常:"+e.getMessage());
            throw new Exception("Error occur execute " +
                    "HttpRemoteProxy.performImpl(), the caused by " + e);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (os != null) {
                os.close();
            }
//            if (in != null) {
//                in.close();
//            }
        }
        return buffer.toString();
    }    

 

public static String doHttpPostRequest(String url, Object bean) throws Exception {
        PostMethod postMethod = new PostMethod(url);

        try {
            postMethod.getParams().setContentCharset("utf-8");
            for (Field field : bean.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                postMethod.setParameter(field.getName(), field.get(bean) == null ? "" : field.get(bean).toString());
            }
            getHttpClient().executeMethod(postMethod);
            if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString(200);
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            postMethod.releaseConnection();
            if (postMethod != null) {
                postMethod = null;
            }
        }
        return null;
    }

 

使用方法调用时应注意如果为get方法调用,应当将参数也放在urlStr里边,param传一个空字符串即可,否则会有错误,底边几个调用方法与此一样

 

返回值为String

public String getResult(URL url,String sendMsg,String type){
        String myResponse = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if("1".equals(type)){
                conn.setRequestMethod("POST");
            }else if("2".equals(type)){
                conn.setRequestMethod("GET");
            }    
               conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
               conn.setDoOutput(true);
               conn.setDoInput(true);

               OutputStream os = conn.getOutputStream();
               DataOutputStream dos = new DataOutputStream(os);
               dos.write(sendMsg.getBytes("UTF-8"));
               dos.flush();
               dos.close();
               os.close();

               InputStream is = conn.getInputStream();
               DataInputStream dis = new DataInputStream(is);
               byte[] receivedBytes = new byte[dis.available()];
               dis.read(receivedBytes);
               myResponse = new String(receivedBytes);
               System.out.println(myResponse);
               dis.close();
               is.close();
               conn.disconnect();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return myResponse;
    }

 

返回值为String

public static String changeUrlStr(URL url, String sendMsg) {
        StringBuffer buffer = null;
        InputStreamReader reader = null;            
        InputStream in = null;
        OutputStreamWriter out = null;
        URLConnection conn = null;
        try {
            int c=0;
            conn = url.openConnection();
            conn.setDoOutput(true);// 设置输出流
            conn.setConnectTimeout(30*1000);
            conn.setReadTimeout(30*1000);
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");// 得到输出流
            out.write(sendMsg);// 输出post数据
            out.flush();
            out.close();
            conn.connect();
            //in = conn.getInputStream();// 得到返回的输入流
            buffer = new StringBuffer();
            reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
            while ((c = reader.read()) != -1) {
                buffer.append((char) c);
            }
            return buffer.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

 

 

返回值为java.io.InputStream类型

/**

*url为接口地址 sendMsg为参数

*/

public static InputStream changeUrl(URL url, String sendMsg) {
        try {
            InputStream in = null;
            OutputStreamWriter out = null;
            URLConnection conn = null;
            conn = url.openConnection();
            conn.setDoOutput(true);// 设置输出流
            conn.setConnectTimeout(30*1000);
            conn.setReadTimeout(30*1000);
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");// 得到输出流
            out.write(sendMsg);// 输出post数据
            out.flush();
            out.close();
            conn.connect();
            in = conn.getInputStream();// 得到返回的输入流
            return in;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
调用 Web Service 接口通常分为以下几个步骤: 1. 确定 Web Service 的地址:获取 Web Service 的 URL,该 URL 是用于访问 Web Service 的唯一标识。 2. 选择合适的调用方式:根据 Web Service 的要求,选择适当的调用方式。常见的调用方式包括 SOAP 和 REST。 - SOAP(Simple Object Access Protocol):基于 XML 的协议,使用 SOAP 调用需要构造 SOAP 消息,并将其发送到 Web Service 的 URL。 - REST(Representational State Transfer):基于 HTTP 协议的一种轻量级架构风格,使用 REST 调用通常通过 HTTP 方法(GET、POST、PUT、DELETE)和 URL 参数进行操作。 3. 构造请求:根据 Web Service 的要求,构造符合格式要求的请求数据。对于 SOAP 调用,需要构造符合 SOAP 协议格式的 XML 请求消息;对于 REST 调用,通常是通过构造合适的 URL 和参数来发送请求。 4. 发送请求获取响应:使用编程语言或工具发送请求到 Web Service 的 URL,并获取接口返回的响应数据。根据调用方式不同,可以使用不同的方法来发送请求获取响应。 5. 解析和处理响应:根据接口返回的数据格式,解析响应数据并进行相应的处理。对于 SOAP 调用,通常需要解析 XML 数据;对于 REST 调用,通常是解析 JSON 或其他数据格式。 具体的调用方式和实现细节会根据不同的编程语言和工具有所不同,您可以根据自己的需求选择合适的方式来进行调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值