blob: 77ffe6250bcd46f8d046df1d90559309b3139cd5 [file] [log] [blame]
Mark Slee7d5da162006-10-10 01:38:25 +00001package com.facebook.thrift.transport;
2
3import java.io.ByteArrayOutputStream;
4import java.io.InputStream;
5import java.io.IOException;
6
7import java.net.URL;
8import java.net.HttpURLConnection;
9
10/**
11 * HTTP implementation of the TTransport interface. Used for working with a
12 * Thrift web services implementation.
13 *
14 * @author Mark Slee <mcslee@facebook.com>
15 */
16public class THttpClient extends TTransport {
17
18 private URL url_ = null;
19
20 private final ByteArrayOutputStream requestBuffer_ =
21 new ByteArrayOutputStream();
22
23 private InputStream inputStream_ = null;
24
25 private int connectTimeout_ = 0;
26
27 private int readTimeout_ = 0;
28
29 public THttpClient(String url) throws TTransportException {
30 try {
31 url_ = new URL(url);
32 } catch (IOException iox) {
33 throw new TTransportException(iox);
34 }
35 }
36
37 public void setConnectTimeout(int timeout) {
38 connectTimeout_ = timeout;
39 }
40
41 public void setReadTimeout(int timeout) {
42 readTimeout_ = timeout;
43 }
44
45 public void open() {}
46
47 public void close() {}
48
49 public boolean isOpen() {
50 return true;
51 }
52
53 public int read(byte[] buf, int off, int len) throws TTransportException {
54 if (inputStream_ == null) {
55 throw new TTransportException("Response buffer is empty, no request.");
56 }
57 try {
58 int ret = inputStream_.read(buf, off, len);
59 if (ret == -1) {
60 throw new TTransportException("No more data available.");
61 }
62 return ret;
63 } catch (IOException iox) {
64 throw new TTransportException(iox);
65 }
66 }
67
68 public void write(byte[] buf, int off, int len) {
69 requestBuffer_.write(buf, off, len);
70 }
71
72 public void flush() throws TTransportException {
73 // Extract request and reset buffer
74 byte[] data = requestBuffer_.toByteArray();
75 requestBuffer_.reset();
76
77 try {
78 // Create connection object
79 HttpURLConnection connection = (HttpURLConnection)url_.openConnection();
80
81 // Timeouts, only if explicitly set
82 if (connectTimeout_ > 0) {
83 connection.setConnectTimeout(connectTimeout_);
84 }
85 if (readTimeout_ > 0) {
86 connection.setReadTimeout(readTimeout_);
87 }
88
89 // Make the request
90 connection.setRequestMethod("POST");
91 connection.setRequestProperty("Content-Type", "application/x-thrift");
92 connection.setRequestProperty("Accept", "application/x-thrift");
93 connection.setRequestProperty("User-Agent", "Java/THttpClient");
94 connection.setDoOutput(true);
95 connection.connect();
96 connection.getOutputStream().write(data);
97
98 int responseCode = connection.getResponseCode();
99 if (responseCode != HttpURLConnection.HTTP_OK) {
100 throw new TTransportException("HTTP Response code: " + responseCode);
101 }
102
103 // Read the responses
104 inputStream_ = connection.getInputStream();
105
106 } catch (IOException iox) {
107 throw new TTransportException(iox);
108 }
109 }
110}