public class HttpStream extends Stream
Here is an example showing a rest consumer class managing data from an restful webservice:
import totalcross.io.IOException;
import totalcross.net.HttpStream;
import totalcross.net.URI;
import totalcross.net.UnknownHostException;
import totalcross.net.ssl.SSLSocketFactory;
import totalcross.sys.Vm;
public class RestConsumerApplication {
public static final String CONTENT_TYPE_JSON = "application/json";
public static void printResponse (HttpStream hs) {
byte[] buf = new byte[hs.contentLength];
try {
hs.readBytes(buf, 0, hs.contentLength);
Vm.debug("status:" + hs.getStatus());
Vm.debug("response:" + new String(buf));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
String getString = "https://jsonplaceholder.typicode.com/posts/1";
String postString = "https://jsonplaceholder.typicode.com/posts";
String putString = "https://jsonplaceholder.typicode.com/posts/1";
String deleteString = "https://jsonplaceholder.typicode.com/posts/1";
String patchString = "https://jsonplaceholder.typicode.com/posts/1";
HttpStream httpStream ;
HttpStream.Options options = new HttpStream.Options();
options.socketFactory = new SSLSocketFactory(); // In case https protocol is required
Vm.debug("============= GET ==============");
options.httpType = HttpStream.GET;
httpStream = new HttpStream(new URI(getString), options);
printResponse(httpStream);
Vm.debug("============= POST ==============");
options.httpType = HttpStream.POST;
options.setContentType(CONTENT_TYPE_JSON);
options.data = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
httpStream = new HttpStream(new URI(postString), options);
printResponse(httpStream);
Vm.debug("============= PUT ==============");
options.httpType = HttpStream.PUT;
options.data = "{\"id\": 1, \"title\": \"new title\", \"body\": \"bar\", \"userId\": 1}";
httpStream = new HttpStream(new URI(putString), options);
printResponse(httpStream);
Vm.debug("============= PATCH ==============");
options.httpType = HttpStream.PATCH;
options.data = "{\"title\": \"new title 2\"}";
httpStream = new HttpStream(new URI(patchString), options);
printResponse(httpStream);
Vm.debug("============= DELETE ==============");
options.httpType = HttpStream.DELETE;
httpStream = new HttpStream(new URI(deleteString), options);
printResponse(httpStream);
}
}
See also the HttpConn
wrapper and the enumeration of common HTTP methods.
HttpConn abstracts dozens of stuff and is totally free to use and modify.| Modifier and Type | Class and Description |
|---|---|
static class |
HttpStream.Options
This static class is used by one of the constructor methods.
|
| Modifier and Type | Field and Description |
|---|---|
boolean |
badResponseCode
Returns true if the response code represents an error.
|
protected byte[] |
buffer |
java.lang.String |
connection
READ-ONLY connection status.
|
java.lang.String |
contentEncoding
READ-ONLY encoding.
|
int |
contentLength
READ-ONLY the size of the returned data (-1 if unknown).
|
int |
contentRead
READ-ONLY number of bytes read from the response's content.
|
byte |
contentType
READ-ONLY see the xxx_TYPE enum below.
|
Hashtable |
cookies
READ-ONLY cookies.
|
static boolean |
debugHeader
Set to true to print the header to the debug console.
|
static java.lang.String |
DELETE
Used in the httpType field
|
static java.lang.String |
GET
Used in the httpType field
|
Hashtable |
headers
This Hashtable contains all headers that came in the response that don't belong to the public fields.
|
static byte |
IMAGE_TYPE
Used in the contentType property.
|
URI |
location
READ-ONLY location.
|
protected LineReader |
lr |
static byte |
MULTIPART_TYPE
Used in the contentType property.
|
protected int |
ofsEnd |
protected int |
ofsStart |
static java.lang.String |
PATCH
Used in the httpType field
|
static java.lang.String |
POST
Used in the httpType field
|
static java.lang.String |
PUT
Used in the httpType field
|
protected int |
readPos |
char |
readTokensDelimiter
The delimiter used when reading data using readTokens.
|
boolean |
readTokensDoTrim
This value is passed to the TokenReader created when readTokens is called.
|
int |
responseCode
READ-ONLY should be one of the 20x.
|
int |
sendSleep
This makes a sleep during the send of a file.
|
protected Socket |
socket |
static byte |
TEXT_HTML_TYPE
Used in the contentType property.
|
protected TokenReader |
tr |
static byte |
UNKNOWN_TYPE
Used in the contentType property.
|
ByteString |
version
READ-ONLY HTTP Version.
|
skipBuffer| Modifier | Constructor and Description |
|---|---|
protected |
HttpStream()
Can be overloaded by classes to late-init the data.
|
|
HttpStream(URI uri)
Constructor for a HttpStream with the default options.
|
|
HttpStream(URI uri,
HttpStream.Options options)
Constructor for a HttpStream with specific variant options.
|
| Modifier and Type | Method and Description |
|---|---|
void |
close()
Closes this I/O connection, releasing any associated resources.
|
java.lang.String |
getStatus()
Get a human readable text to describe the current status
of this HttpStream
|
protected void |
init(URI uri,
HttpStream.Options options)
Internal method to initialize this HttpStream
|
boolean |
isOk()
Tell if this HttpStream is functioning properly.
|
Image |
makeImage()
Create the image instance from this HttpStream.
|
int |
readBytes(byte[] buf,
int start,
int count)
Reads bytes from the stream.
|
java.lang.String |
readLine()
Reads a line of text comming from the socket attached to this HttpStream.
|
java.lang.String[] |
readTokens()
Reads a line of text comming from the socket attached to this HttpStream.
|
boolean |
refill()
Refill the buffer, assuming that ofsCur is at ofsEnd.
|
protected boolean |
shouldSendData(HttpStream.Options options) |
protected boolean |
skipToNextMimePart()
Skip to the next mime part.
|
int |
writeBytes(byte[] buf,
int start,
int count)
Writes bytes to the stream.
|
protected void |
writeResponseRequest(java.lang.StringBuffer sb,
HttpStream.Options options) |
asInputStream, asOutputStream, asStream, asStream, skipBytes, wrapInputStream, wrapInputStreamToStream, write, writeBytes, writeBytes, writeBytespublic static boolean debugHeader
public int responseCode
public java.lang.String contentEncoding
public int contentLength
public int contentRead
public byte contentType
public ByteString version
public java.lang.String connection
public URI location
public Hashtable cookies
cookies.getKeys().
If you want to persist a session, just store the cookies sent by the server
and then send them back in each request you make, like this:
public class SessionTest extends MainWindow
{
String url = "http://localhost:8080/servlet/sessionTest";
Button btnGO;
Hashtable cookies;
...
if (event.target == btnGO)
{
HttpStream.Options options = new HttpStream.Options();
// set cookies if they already exist
if (cookies != null)
options.setCookies(cookies);
HttpStream st = new HttpStream(new URI(url),options);
// Save cookies sent by server
if (st.cookies != null)
cookies = st.cookies;
}
...
}
Note that its important that you call Socket.disconnect()
before exiting your application.HttpStream.Options.setCookies(Hashtable)public Hashtable headers
public static final byte UNKNOWN_TYPE
public static final byte TEXT_HTML_TYPE
public static final byte IMAGE_TYPE
public static final byte MULTIPART_TYPE
public static final java.lang.String GET
HttpStream.Options.httpType,
Constant Field Valuespublic static final java.lang.String POST
HttpStream.Options.httpType,
Constant Field Valuespublic static final java.lang.String PUT
HttpStream.Options.httpType,
Constant Field Valuespublic static final java.lang.String PATCH
HttpStream.Options.httpType,
Constant Field Valuespublic static final java.lang.String DELETE
HttpStream.Options.httpType,
Constant Field Valuespublic int sendSleep
public char readTokensDelimiter
readTokens()public boolean readTokensDoTrim
LineReader.doTrim,
readTokens()protected Socket socket
protected int ofsStart
protected int ofsEnd
protected byte[] buffer
protected int readPos
protected LineReader lr
protected TokenReader tr
public boolean badResponseCode
protected HttpStream()
public HttpStream(URI uri) throws UnknownHostException, IOException
uri - to connect toUnknownHostExceptionIOExceptionHttpStream.Optionspublic HttpStream(URI uri, HttpStream.Options options) throws UnknownHostException, IOException
uri - to connect tooptions - the specific options for this HttpStreamUnknownHostExceptionIOExceptionHttpStream.Optionspublic int readBytes(byte[] buf,
int start,
int count)
throws IOException
StreamreadBytes in class Streambuf - the byte array to read data intostart - the start position in the arraycount - the number of bytes to readIOExceptionpublic int writeBytes(byte[] buf,
int start,
int count)
throws IOException
StreamIOException if an error prevented the write
operation from occurring.writeBytes in class Streambuf - the byte array to write data fromstart - the start position in the byte arraycount - the number of bytes to writeIOExceptionpublic void close()
throws IOException
close in interface java.io.Closeableclose in interface java.lang.AutoCloseableIOException - If an I/O error occurs.protected void init(URI uri, HttpStream.Options options) throws UnknownHostException, IOException
URI - uri to connect tooptions - the specific options for this HttpStreamIOExceptionUnknownHostExceptionprotected boolean shouldSendData(HttpStream.Options options)
protected void writeResponseRequest(java.lang.StringBuffer sb,
HttpStream.Options options)
throws IOException
IOExceptionpublic boolean isOk()
public java.lang.String getStatus()
public final boolean refill()
throws IOException
IOExceptionpublic Image makeImage() throws ImageException, IOException
ImageExceptionIOExceptionprotected boolean skipToNextMimePart()
throws IOException
IOException - Actually, we only handle the first mime part This code might later be
extended for other parts.public java.lang.String readLine()
throws IOException
null if nothing was read.IOExceptionreadTokens()public java.lang.String[] readTokens()
throws IOException
null if nothing was read.IOExceptionreadTokensDelimiter,
readTokensDoTrim,
readLine()