summaryrefslogtreecommitdiffstats
path: root/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java
blob: 438c70c2333b8652996a3a27aab64e86aac33ae5 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// --- BEGIN COPYRIGHT BLOCK ---
// 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; version 2 of the License.
//
// 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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cmsutil.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;

import com.netscape.cmsutil.net.ISocketFactory;

/**
 * basic http client.
 * not optimized for performance.
 * handles only string content.
 */
public class HttpClient {
    protected ISocketFactory mFactory = null;

    protected Socket mSocket = null;
    protected InputStream mInputStream = null;
    protected OutputStream mOutputStream = null;

    protected InputStreamReader mInputStreamReader = null;
    protected OutputStreamWriter mOutputStreamWriter = null;
    protected BufferedReader mBufferedReader = null;
    protected SSLCertificateApprovalCallback mCertApprovalCallback = null;
    protected boolean mConnected = false;

    public HttpClient() {
    }

    public HttpClient(ISocketFactory factory) {
        mFactory = factory;
    }

    public HttpClient(ISocketFactory factory, SSLCertificateApprovalCallback certApprovalCallback) {
        mFactory = factory;
        mCertApprovalCallback = certApprovalCallback;
    }

    public void connect(String host, int port)
            throws IOException {
        if (mFactory != null) {
            if (mCertApprovalCallback == null) {
                mSocket = mFactory.makeSocket(host, port);
            } else {
                mSocket = mFactory.makeSocket(host, port, mCertApprovalCallback, null);
            }
        } else {
            mSocket = new Socket(host, port);
        }

        if (mSocket == null) {
            IOException e = new IOException("Couldn't make connection");

            throw e;
        }

        mInputStream = mSocket.getInputStream();
        mOutputStream = mSocket.getOutputStream();
        mInputStreamReader = new InputStreamReader(mInputStream, "UTF8");
        mBufferedReader = new BufferedReader(mInputStreamReader);
        mOutputStreamWriter = new OutputStreamWriter(mOutputStream, "UTF8");
        mConnected = true;
    }

    // Inserted by beomsuk
    public void connect(String host, int port, int timeout)
            throws IOException {
        if (mFactory != null) {
            mSocket = mFactory.makeSocket(host, port, timeout);
        } else {
            mSocket = new Socket(host, port);
        }

        if (mSocket == null) {
            IOException e = new IOException("Couldn't make connection");

            throw e;
        }

        mInputStream = mSocket.getInputStream();
        mOutputStream = mSocket.getOutputStream();
        mInputStreamReader = new InputStreamReader(mInputStream, "UTF8");
        mBufferedReader = new BufferedReader(mInputStreamReader);
        mOutputStreamWriter = new OutputStreamWriter(mOutputStream, "UTF8");
        mConnected = true;
    }

    // Insert end
    public boolean connected() {
        return mConnected;
    }

    /**
     * Sends a request to http server.
     * Returns a http response.
     */
    public HttpResponse send(HttpRequest request)
            throws IOException {
        HttpResponse resp = new HttpResponse();

        if (mOutputStream == null)
            throw new IOException("Output stream not initialized");
        request.write(mOutputStreamWriter);
        try {
            resp.parse(mBufferedReader);
        } catch (IOException e) {
            // XXX should we disconnect in all cases ?
            disconnect();
            throw e;
        }
        disconnect();
        return resp;
    }

    public void disconnect()
            throws IOException {
        mSocket.close();
        mInputStream = null;
        mOutputStream = null;
        mConnected = false;
    }

    public InputStream getInputStream() {
        return mInputStream;
    }

    public OutputStream getOutputStream() {
        return mOutputStream;
    }

    public BufferedReader getBufferedReader() {
        return mBufferedReader;
    }

    public InputStreamReader getInputStreamReader() {
        return mInputStreamReader;
    }

    public OutputStreamWriter getOutputStreamWriter() {
        return mOutputStreamWriter;
    }

    public Socket getSocket() {
        return mSocket;
    }

    /**
     * unit test
     */
    public static void main(String args[])
            throws Exception {
        HttpClient c = new HttpClient();
        HttpRequest req = new HttpRequest();
        HttpResponse resp = null;

        System.out.println("connecting to " + args[0] + " " + args[1]);
        c.connect(args[0], Integer.parseInt(args[1]));

        req.setMethod("GET");
        req.setURI(args[2]);
        if (args.length >= 4)
            req.setHeader("Connection", args[3]);
        resp = c.send(req);

        System.out.println("version " + resp.getHttpVers());
        System.out.println("status code " + resp.getStatusCode());
        System.out.println("reason " + resp.getReasonPhrase());
        System.out.println("content " + resp.getContent());

        //String lenstr = resp.getHeader("Content-Length");
        //System.out.println("content len is "+lenstr);
        //int length = Integer.parseInt(lenstr);
        //char[] content = new char[length];
        //c.mBufferedReader.read(content, 0, content.length);
        //System.out.println(content);

        if (args.length >= 4 && args[3].equalsIgnoreCase("keep-alive")) {
            for (int i = 0; i < 2; i++) {
                if (i == 1)
                    req.setHeader("Connection", "Close");
                resp = c.send(req);
                System.out.println("version " + resp.getHttpVers());
                System.out.println("status code " + resp.getStatusCode());
                System.out.println("reason " + resp.getReasonPhrase());
                System.out.println("content " + resp.getContent());
                //len = Integer.parseInt(resp.getHeader("Content-Length"));
                //System.out.println("content len is "+len);
                //msgbody = new char[len];
                //c.mBufferedReader.read(msgbody, 0, len);
                //System.out.println(content);
            }
        }
    }
}