Java调用C#写的web服务接口(含https调用)

来源:互联网 发布:红米清空数据失败 编辑:程序博客网 时间:2024/06/16 23:34

C#语言写的web服务接口可以使用Java语言调用

参考:http://www.yoodb.com/article/display/1034

            http://www.ithtw.com/3465.html

(1)引用库类,需要同时添加org.apache.commons.httpclient,org.apache.commons.loggging,org.apache.commons.codec等jar文件供内部调用

import java.io.IOException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.ByteArrayOutputStream;import java.io.InputStream;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.commons.codec.digest.DigestUtils;import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.commons.httpclient.methods.StringRequestEntity;import org.apache.commons.httpclient.protocol.Protocol;import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

(2)get方式

      public String getHttp(String url) {        String responseMsg = "";               HttpClient httpClient = new HttpClient();        GetMethod getMethod = new GetMethod(url);        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());        try {            httpClient.executeMethod(getMethod);            ByteArrayOutputStream out = new ByteArrayOutputStream();            InputStream in = getMethod.getResponseBodyAsStream();            int len = 0;            byte[] buf = new byte[1024];            while((len=in.read(buf))!=-1){                out.write(buf, 0, len);            }            responseMsg = out.toString("UTF-8");        } catch (HttpException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            //释放连接            getMethod.releaseConnection();        }        return responseMsg;    }
(3)post方式,直接发送json数据方法

     public String postHttp(String url) throws UnsupportedEncodingException {        String responseMsg = "";        String json = "{\"deviceId\":\"efb2bb7d8572410f38430a641d690735\",\"enterpriseCode\":\"522300000010201\",\"data\": [{\"dataCode\":\"00-00-010100-10\",\"dataValue\":\"2441.82\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"},{\"dataCode\":\"00-00-022200-10\",\"dataValue\":\"0\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"},{\"dataCode\":\"00-00-023300-60\",\"dataValue\":\"9917642\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"}],\"RESTCODE\":\"c0a7cc24-1e13-47b7-8115-eaa630a95bb8\"}";                        HttpClient httpClient = new HttpClient();        httpClient.getParams().setContentCharset("UTF-8");        PostMethod postMethod = new PostMethod(url);        //postMethod.addParameter(type, code);        /*postMethod.addParameter("client_id", "123");        postMethod.addParameter("client_secret", "456");*/        RequestEntity entity = new StringRequestEntity(json,"application/json", "UTF-8");        postMethod.setRequestEntity(entity);        try {            httpClient.executeMethod(postMethod);            ByteArrayOutputStream out = new ByteArrayOutputStream();            InputStream in = postMethod.getResponseBodyAsStream();            int len = 0;            byte[] buf = new byte[1024];            while((len=in.read(buf))!=-1){                out.write(buf, 0, len);            }            responseMsg = out.toString("UTF-8");        } catch (HttpException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            postMethod.releaseConnection();        }        return responseMsg;    }

(4)post方式,发送参数数据方法

     public String postHttp(String url) throws UnsupportedEncodingException {        String responseMsg = "";        HttpClient httpClient = new HttpClient();        httpClient.getParams().setContentCharset("UTF-8");        PostMethod postMethod = new PostMethod(url);        //postMethod.addParameter(type, code);        postMethod.addParameter("client_id", "123");        postMethod.addParameter("client_secret", "456");        try {            httpClient.executeMethod(postMethod);            ByteArrayOutputStream out = new ByteArrayOutputStream();            InputStream in = postMethod.getResponseBodyAsStream();            int len = 0;            byte[] buf = new byte[1024];            while((len=in.read(buf))!=-1){                out.write(buf, 0, len);            }            responseMsg = out.toString("UTF-8");        } catch (HttpException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            postMethod.releaseConnection();        }        return responseMsg;    }

(5)post到https接口

     public String postHttps(String url) throws UnsupportedEncodingException {        String responseMsg = "";        String json = "{\"deviceId\":\"efb2bb7d8572410f38430a641d690735\",\"enterpriseCode\":\"522300000010201\",\"data\": [{\"dataCode\":\"00-00-010100-10\",\"dataValue\":\"2441.82\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"},{\"dataCode\":\"00-00-022200-10\",\"dataValue\":\"0\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"},{\"dataCode\":\"00-00-023300-60\",\"dataValue\":\"9917642\",\"inputType\":\"5\",\"statDate\":\"2016-07-20 23:59:59\",\"uploadDate\":\"2016-07-22 09:32:43\",\"statType\":\"1\",\"scope\":\"1\",\"valid\":\"true\"}],\"RESTCODE\":\"c0a7cc24-1e13-47b7-8115-eaa630a95bb8\"}";                ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();Protocol.registerProtocol("https", new Protocol("https", fcty, 4002));        HttpClient httpClient = new HttpClient();        httpClient.getParams().setContentCharset("UTF-8");        PostMethod postMethod = new PostMethod(url);        //postMethod.addParameter(type, code);        /*postMethod.addParameter("client_id", "123");        postMethod.addParameter("client_secret", "456");*/        RequestEntity entity = new StringRequestEntity(json,"application/json", "UTF-8");        postMethod.setRequestEntity(entity);        try {            httpClient.executeMethod(postMethod);            ByteArrayOutputStream out = new ByteArrayOutputStream();            InputStream in = postMethod.getResponseBodyAsStream();            int len = 0;            byte[] buf = new byte[1024];            while((len=in.read(buf))!=-1){                out.write(buf, 0, len);            }            responseMsg = out.toString("UTF-8");        } catch (HttpException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            postMethod.releaseConnection();        }        return responseMsg;    }

(6)实现对https接口的访问,需要实现以下接口X509TrustManager和ProtocolSocketFactory

         X509TrustManager接口实现

import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;public class MyX509TrustManager implements X509TrustManager {   /*    * (non-Javadoc)    * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[],    * java.lang.String)    */   public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {   }   /*    * (non-Javadoc)    * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],    * java.lang.String)    */   public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {   }   /*    * (non-Javadoc)    * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()    */   public X509Certificate[] getAcceptedIssuers() {       return null;   }}
ProtocolSocketFactory接口实现:

import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException; import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.ConnectTimeoutException;import org.apache.commons.httpclient.HttpClientError;import org.apache.commons.httpclient.params.HttpConnectionParams;import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory, ProtocolSocketFactory {     private SSLContext sslContext = null;     /**     * Constructor for MySecureProtocolSocketFactory.     */    public MySecureProtocolSocketFactory() {    }     /**     * @return     */    private static SSLContext createEasySSLContext() {        try {            SSLContext context = SSLContext.getInstance("SSL");            context.init(null, new TrustManager[] {new MyX509TrustManager()}, null);            return context;        } catch (Exception e) {            throw new HttpClientError(e.toString());        }    }     /**     * @return     */    private SSLContext getSSLContext() {        if (this.sslContext == null) {            this.sslContext = createEasySSLContext();        }        return this.sslContext;    }     /*     * (non-Javadoc)     * @see     * org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,     * int, java.net.InetAddress, int)     */    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException,        UnknownHostException {         return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);    }     /*     * (non-Javadoc)     * @see     * org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,     * int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams)     */    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort,            final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {        if (params == null) {            throw new IllegalArgumentException("Parameters may not be null");        }        int timeout = params.getConnectionTimeout();        if (timeout == 0) {            return createSocket(host, port, localAddress, localPort);        } else {            return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout);        }    }     /*     * (non-Javadoc)     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)     */    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {        return getSSLContext().getSocketFactory().createSocket(host, port);    }     /*     * (non-Javadoc)     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)     */    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,        UnknownHostException {        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);    }}


0 0
原创粉丝点击