⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpclientconnection.java

📁 实现了SyncML无线同步协议
💻 JAVA
字号:
/** * Copyright (C) 2003-2004 Funambol * *  This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */package sync4j.test.tools;import sync4j.framework.core.Constants;import sync4j.framework.core.Util;import sync4j.framework.core.SyncML;import sync4j.framework.core.Constants;import sync4j.framework.core.RepresentationException;import sync4j.framework.core.Sync4jException;import sync4j.framework.tools.WBXMLTools;import java.net.*;import java.io.*;import java.util.logging.Logger;import java.util.logging.Level;import org.jibx.runtime.*;import org.jibx.runtime.impl.*;/** * * @version $Id: HttpClientConnection.java,v 1.3 2004/06/01 19:50:48 luigiafassina Exp $ * */public final class HttpClientConnection {    public static String LOG_NAME = "sync4j.test.tools.PostSyncML";    private static final Logger log = Logger.getLogger(LOG_NAME);    //    // todo : decide if HttpURLConnection is a good implementation strategy...    // The other way to implement this would be to use a java.net.Socket    // The problem with java.net.Socket is that I'd have to write alot    // of low-level HTTP protocol code.  The advantage of java.net.Socket    // is that I could explicitly set a Socket timeout value. Hmm....    //    // Also, another way to implement this class would be to use Apache's    // HttpClient code:  http://jakarta.apache.org/commons/httpclient/    //    private final HttpURLConnection  conn;    private       OutputStream       out;    private final String             serverAddress;    private       String             lastResponse;  // as string    private       String             lastMessage;  // as string    /**     *     * @param strServerAddress must be non-null     *     */    public HttpClientConnection(final String strServerAddress)    throws IOException    {        if (strServerAddress == null)        {            throw new NullPointerException("strServerAddress parameter is null");        }        serverAddress = strServerAddress;        if (serverAddress.startsWith("http:") == false)        {            throw new IllegalArgumentException(                    "server address must start with 'http:'");        }        URL u = null;        try        {            u = new URL(serverAddress);        }        catch (java.net.MalformedURLException ex)        {            throw new IllegalArgumentException(                    "server address is not a valid URL");        }        lastMessage = lastResponse = null;        Object obj = u.openConnection();        if ((obj instanceof java.net.HttpURLConnection) == false)        {            // todo : throw exception here        }        conn = (HttpURLConnection) obj;        conn.setDoOutput(true);        conn.setDoInput(true);        conn.setAllowUserInteraction(false);        conn.setRequestMethod("POST");        conn.setUseCaches(false);        conn.setInstanceFollowRedirects(false);        conn.setRequestProperty("User-Agent", this.getClass().toString());    }    public SyncML sendMessage(final SyncML msg) throws Exception {        String syncML = marshallSyncML(msg);        return sendMessage(syncML);    }    public SyncML sendMessage(final String msg)    throws IOException, Sync4jException, RepresentationException {        final byte[] yaData = msg.getBytes();        conn.setRequestProperty("Content-Type", Constants.MIMETYPE_SYNCML_XML);        conn.setRequestProperty("Content-Length", "" + yaData.length);        out = conn.getOutputStream();        out.write(yaData);        out.flush();        InputStream in = conn.getInputStream();        final int iResponseCode = conn.getResponseCode();        if (iResponseCode != HttpURLConnection.HTTP_OK) {            String error = "Response status: "                         + iResponseCode                         + ", Response message: "                         + conn.getResponseMessage()                         ;            throw new IOException(error);        }        final String strResponseContentType = conn.getContentType();        if (strResponseContentType == null)        {            throw new IOException("Content type: " + strResponseContentType);        }        if (strResponseContentType.equals(Constants.MIMETYPE_SYNCML_XML) == false)        {            throw new IOException( "Content type: "                                 + strResponseContentType                                 + " (should be "                                 + Constants.MIMETYPE_SYNCML_XML                                 + ")"                                 );        }        lastMessage = msg;        final int iResponseContentLength = conn.getContentLength();        if (iResponseContentLength < 1)        {           throw new IOException("Response content length: " + iResponseContentLength);        }        final byte[] yaResponse = new byte[iResponseContentLength];        int n = 0;        int iBytesRead = 0;        do        {            n = in.read(yaResponse,                    iBytesRead,                    yaResponse.length - iBytesRead);            if (n > 0)            {                iBytesRead += n;            }        } while (n != -1);        if (iBytesRead != iResponseContentLength)        {            // todo : throw exception - ?        }        lastResponse = new String(yaResponse);        SyncML syncML = null;        try {            syncML = unmarshallSyncML(lastResponse);        } catch(Exception e) {            throw new Sync4jException(e);        }        return syncML;    }    public SyncML sendWBXMLMessage(final byte[] msg)    throws IOException, Sync4jException, RepresentationException    {        final byte[] yaData = msg;        conn.setRequestProperty("Content-Type", Constants.MIMETYPE_SYNCML_WBXML);        conn.setRequestProperty("Content-Length", "" + yaData.length);        out = conn.getOutputStream();        out.write(yaData);        out.flush();        InputStream in = conn.getInputStream();        final int iResponseCode = conn.getResponseCode();        if (iResponseCode != HttpURLConnection.HTTP_OK)        {            String error = "Response status: "                         + iResponseCode                         + ", Response message: "                         + conn.getResponseMessage()                         ;            throw new IOException(error);        }        final String strResponseContentType = conn.getContentType();        if (strResponseContentType == null)        {            throw new IOException("Content type: " + strResponseContentType);        }        if (strResponseContentType.equals(Constants.MIMETYPE_SYNCML_WBXML) == false)        {            throw new IOException( "Content type: "                                 + strResponseContentType                                 + " (should be "                                 + Constants.MIMETYPE_SYNCML_WBXML                                 + ")"                                 );        }        final int iResponseContentLength = conn.getContentLength();        if (iResponseContentLength < 1)        {           throw new IOException("Response content length: " + iResponseContentLength);        }        final byte[] yaResponse = new byte[iResponseContentLength];        int n = 0;        int iBytesRead = 0;        do        {            n = in.read(yaResponse,                    iBytesRead,                    yaResponse.length - iBytesRead);            if (n > 0)            {                iBytesRead += n;            }        } while (n != -1);        if (iBytesRead != iResponseContentLength)        {            // todo : throw exception - ?        }        //        //TRN - convert yaResponse from WBXML to XML string, then create the Message        //        String xmlResponse = WBXMLTools.wbxmlToXml(yaResponse);        SyncML syncML = null;        try {            syncML = unmarshallSyncML(xmlResponse);        } catch(Exception e) {            throw new Sync4jException(e);        }        return syncML;    }    public void close()    {        if (conn != null)        {            conn.disconnect();            try            {                out.close();            }            catch (java.io.IOException ex)            {                // ignore exception            }        }    }    public String toString()    {        return serverAddress;    }    public String getLastMessage() {        return lastMessage;    }    public String getLastResponse() {        return lastResponse;    }    private SyncML unmarshallSyncML(String response) throws Sync4jException {        SyncML syncML = null;        try {            IBindingFactory f = BindingDirectory.getFactory(SyncML.class);            IUnmarshallingContext c = f.createUnmarshallingContext();            syncML = (SyncML)c.unmarshalDocument(new ByteArrayInputStream(response.getBytes()), null);        } catch(org.jibx.runtime.JiBXException e) {            e.printStackTrace();            throw new Sync4jException(e);        }        return syncML;    }    private String marshallSyncML(SyncML syncML) throws Sync4jException {        String msg = null;        try {            ByteArrayOutputStream bout = new ByteArrayOutputStream();            IBindingFactory f = BindingDirectory.getFactory(SyncML.class);            IMarshallingContext c = f.createMarshallingContext();            c.setIndent(0);            c.marshalDocument(syncML, "UTF-8", null, bout);            msg = new String(bout.toByteArray());        } catch(Exception e) {            e.printStackTrace();            throw new Sync4jException(e);        }        return msg;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -