APIdia Launch Partner
Top Description Inners Methods
com.badlogic.gdx

public Interface Net

Imports
java.io.InputStream, .OutputStream, java.util.HashMap, .List, .Map, com.badlogic.gdx.Application.ApplicationType, com.badlogic.gdx.net.HttpRequestHeader, .HttpResponseHeader, .HttpStatus, .ServerSocket, .ServerSocketHints, .Socket, .SocketHints, com.badlogic.gdx.utils.GdxRuntimeException, .Null, .Pool.Poolable

Provides methods to perform networking operations, such as simple HTTP get and post requests, and TCP server/client socket communication.

To perform an HTTP request create a HttpRequest with the HTTP method (see HttpMethods for common methods) and invoke sendHttpRequest(HttpRequest, HttpResponseListener) with it and a HttpResponseListener. After the HTTP request was processed, the HttpResponseListener is called with a HttpResponse with the HTTP response values and an status code to determine if the request was successful or not.

To create a TCP client socket to communicate with a remote TCP server, invoke the newClientSocket(Protocol, String, int, SocketHints) method. The returned Socket offers an InputStream and OutputStream to communicate with the end point.

To create a TCP server socket that waits for incoming connections, invoke the newServerSocket(Protocol, int, ServerSocketHints) method. The returned ServerSocket offers an ServerSocket#accept(SocketHints options) method that waits for an incoming connection.
Authors
mzechner, noblemaster, arielsan

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static interface
Net.HttpMethods

Provides common HTTP methods to use when creating a HttpRequest.

public static class
Net.HttpRequest

Contains getters and setters for the following parameters:

  • httpMethod: GET or POST are most common, can use HttpMethods for static references
  • url: the url
  • headers: a map of the headers, setter can be called multiple times
  • timeout: time spent trying to connect before giving up
  • content: A string containing the data to be used when processing the HTTP request.
public static interface
Net.HttpResponse

HTTP response interface with methods to get the response data as a byte[], a String or an InputStream.

public static interface
Net.HttpResponseListener

Listener to be able to do custom logic once the HttpResponse is ready to be processed, register it with Net#sendHttpRequest(HttpRequest, HttpResponseListener).

public static enum

Method Summary

Modifier and TypeMethod and Description
public void
public boolean
public Socket
newClientSocket(Net.Protocol protocol, String
the host address
host
,
int
the port
port
,
SocketHints
additional SocketHints used to create the socket. Input null to use the default setting provided by the system.
hints
)

Creates a new TCP client socket that connects to the given host and port.

public ServerSocket

Returns:

the ServerSocket
newServerSocket
(Net.Protocol protocol, String
the hostname or ip address to bind the socket to
hostname
,
int
the port to listen on
port
,
ServerSocketHints
additional ServerSocketHints used to create the socket. Input null to use the default setting provided by the system.
hints
)

Creates a new server socket on the given address and port, using the given Protocol, waiting for incoming connections.

public ServerSocket

Returns:

the ServerSocket
newServerSocket
(Net.Protocol protocol, int
the port to listen on
port
,
ServerSocketHints
additional ServerSocketHints used to create the socket. Input null to use the default setting provided by the system.
hints
)

Creates a new server socket on the given port, using the given Protocol, waiting for incoming connections.

public boolean

Returns:

false if it is known the uri was not opened, true otherwise.
openURI
(String
the URI to be opened.
URI
)

Launches the default browser to display a URI.

public void
sendHttpRequest(Net.HttpRequest
The HttpRequest to be performed.
httpRequest
,
Net.HttpResponseListener
The HttpResponseListener to call once the HTTP response is ready to be processed. Could be null, in that case no listener is called.
httpResponseListener
)

Process the specified HttpRequest and reports the HttpResponse to the specified HttpResponseListener.

Method Detail

cancelHttpRequestback to summary
public void cancelHttpRequest(Net.HttpRequest httpRequest)
isHttpRequestPendingback to summary
public boolean isHttpRequestPending(Net.HttpRequest httpRequest)
newClientSocketback to summary
public Socket newClientSocket(Net.Protocol protocol, String host, int port, SocketHints hints)

Creates a new TCP client socket that connects to the given host and port.

Parameters
host:String

the host address

port:int

the port

hints:SocketHints

additional SocketHints used to create the socket. Input null to use the default setting provided by the system.

Exceptions
GdxRuntimeException:
in case the socket couldn't be opened
newServerSocketback to summary
public ServerSocket newServerSocket(Net.Protocol protocol, String hostname, int port, ServerSocketHints hints)

Creates a new server socket on the given address and port, using the given Protocol, waiting for incoming connections.

Parameters
hostname:String

the hostname or ip address to bind the socket to

port:int

the port to listen on

hints:ServerSocketHints

additional ServerSocketHints used to create the socket. Input null to use the default setting provided by the system.

Returns:ServerSocket

the ServerSocket

Exceptions
GdxRuntimeException:
in case the socket couldn't be opened
newServerSocketback to summary
public ServerSocket newServerSocket(Net.Protocol protocol, int port, ServerSocketHints hints)

Creates a new server socket on the given port, using the given Protocol, waiting for incoming connections.

Parameters
port:int

the port to listen on

hints:ServerSocketHints

additional ServerSocketHints used to create the socket. Input null to use the default setting provided by the system.

Returns:ServerSocket

the ServerSocket

Exceptions
GdxRuntimeException:
in case the socket couldn't be opened
openURIback to summary
public boolean openURI(String URI)

Launches the default browser to display a URI. If the default browser is not able to handle the specified URI, the application registered for handling URIs of the specified type is invoked. The application is determined from the protocol and path of the URI. A best effort is made to open the given URI; however, since external applications are involved, no guarantee can be made as to whether the URI was actually opened. If it is known that the URI was not opened, false will be returned; otherwise, true will be returned.

Parameters
URI:String

the URI to be opened.

Returns:boolean

false if it is known the uri was not opened, true otherwise.

sendHttpRequestback to summary
public void sendHttpRequest(Net.HttpRequest httpRequest, Net.HttpResponseListener httpResponseListener)

Process the specified HttpRequest and reports the HttpResponse to the specified HttpResponseListener.

Parameters
httpRequest:Net.HttpRequest

The HttpRequest to be performed.

httpResponseListener:Net.HttpResponseListener

The HttpResponseListener to call once the HTTP response is ready to be processed. Could be null, in that case no listener is called.

com.badlogic.gdx back to summary

public Interface Net.HttpMethods


Provides common HTTP methods to use when creating a HttpRequest.

Field Summary

Modifier and TypeField and Description
public static final String
DELETE

The DELETE method deletes the specified resource.

public static final String
GET

The GET method requests a representation of the specified resource.

public static final String
HEAD

The HEAD method asks for a response identical to that of a GET request, but without the response body.

public static final String
PATCH

The PATCH method is used to apply partial modifications to a resource.

public static final String
POST

The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

public static final String
PUT

The PUT method replaces all current representations of the target resource with the request payload.

Field Detail

DELETEback to summary
public static final String DELETE

The DELETE method deletes the specified resource.

GETback to summary
public static final String GET

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HEADback to summary
public static final String HEAD

The HEAD method asks for a response identical to that of a GET request, but without the response body.

PATCHback to summary
public static final String PATCH

The PATCH method is used to apply partial modifications to a resource.

POSTback to summary
public static final String POST

The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

PUTback to summary
public static final String PUT

The PUT method replaces all current representations of the target resource with the request payload.

com.badlogic.gdx back to summary

public Class Net.HttpRequest

extends Object
implements Poolable
Class Inheritance
All Implemented Interfaces
com.badlogic.gdx.utils.Pool.Poolable

Contains getters and setters for the following parameters: Abstracts the concept of a HTTP Request:
Map parameters = new HashMap();
parameters.put("user", "myuser");

HttpRequest httpGet = new HttpRequest(HttpMethods.Get);
httpGet.setUrl("http://somewhere.net");
httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters));
...
Gdx.net.sendHttpRequest (httpGet, new HttpResponseListener() {
	public void handleHttpResponse(HttpResponse httpResponse) {
		status = httpResponse.getResultAsString();
		//do stuff here based on response
	}

	public void failed(Throwable t) {
		status = "failed";
		//do stuff here based on the failed attempt
	}
});

Field Summary

Modifier and TypeField and Description
private String
private long
private InputStream
private boolean
private Map<String, String>
private String
private boolean
private int
private String

Constructor Summary

AccessConstructor and Description
public
public
HttpRequest(String
This is the HTTP method for the request, see HttpMethods
httpMethod
)

Creates a new HTTP request with the specified HTTP method, see HttpMethods.

Method Summary

Modifier and TypeMethod and Description
public String
getContent()

Returns the content string to be used for the HTTP request.

public long
getContentLength()

Returns the content length in case content is a stream.

public InputStream
getContentStream()

Returns the content stream.

public boolean
getFollowRedirects()

Returns whether 301 and 302 redirects are followed.

public Map<String, String>
getHeaders()

Returns a Map<string, string> with the headers of the HTTP request.

public boolean
getIncludeCredentials()

Returns whether a cross-origin request will include credentials.

public String
getMethod()

Returns the HTTP method of the HttpRequest.

public int

Returns:

the timeOut.
getTimeOut
()

Returns the timeOut of the HTTP request.

public String
getUrl()

Returns the URL of the HTTP request.

public void
reset()

Implements com.badlogic.gdx.utils.Pool.Poolable.reset.

Resets the object for reuse.

public void
setContent(String
A string encoded in the corresponding Content-Encoding set in the headers, with the data to send with the HTTP request. For example, in case of HTTP GET, the content is used as the query string of the GET while on a HTTP POST it is used to send the POST data.
content
)

Sets the content to be used in the HTTP request.

public void
setContent(InputStream
The stream with the content data.
contentStream
,
long contentLength)

Sets the content as a stream to be used for a POST for example, to transmit custom data.

public void
setFollowRedirects(boolean
whether to follow redirects.
followRedirects
)

Sets whether 301 and 302 redirects are followed.

public void
setHeader(String
the name of the header.
name
,
String
the value of the header.
value
)

Sets a header to this HTTP request, see HttpRequestHeader.

public void
setIncludeCredentials(boolean includeCredentials)

Sets whether a cross-origin request will include credentials.

public void
setMethod(String httpMethod)

Sets the HTTP method of the HttpRequest.

public void
setTimeOut(int
the number of milliseconds to wait before giving up, 0 or negative to block until the operation is done
timeOut
)

Sets the time to wait for the HTTP request to be processed, use 0 block until it is done.

public void
setUrl(String
The URL to set.
url
)

Sets the URL of the HTTP request.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

contentback to summary
private String content
contentLengthback to summary
private long contentLength
contentStreamback to summary
private InputStream contentStream
followRedirectsback to summary
private boolean followRedirects
headersback to summary
private Map<String, String> headers
httpMethodback to summary
private String httpMethod
includeCredentialsback to summary
private boolean includeCredentials
timeOutback to summary
private int timeOut
urlback to summary
private String url

Constructor Detail

HttpRequestback to summary
public HttpRequest()
HttpRequestback to summary
public HttpRequest(String httpMethod)

Creates a new HTTP request with the specified HTTP method, see HttpMethods.

Parameters
httpMethod:String

This is the HTTP method for the request, see HttpMethods

Method Detail

getContentback to summary
public String getContent()

Returns the content string to be used for the HTTP request.

getContentLengthback to summary
public long getContentLength()

Returns the content length in case content is a stream.

getContentStreamback to summary
public InputStream getContentStream()

Returns the content stream.

getFollowRedirectsback to summary
public boolean getFollowRedirects()

Returns whether 301 and 302 redirects are followed. By default true. Whether to follow redirects.

getHeadersback to summary
public Map<String, String> getHeaders()

Returns a Map with the headers of the HTTP request.

getIncludeCredentialsback to summary
public boolean getIncludeCredentials()

Returns whether a cross-origin request will include credentials. By default false.

getMethodback to summary
public String getMethod()

Returns the HTTP method of the HttpRequest.

getTimeOutback to summary
public int getTimeOut()

Returns the timeOut of the HTTP request.

Returns:int

the timeOut.

getUrlback to summary
public String getUrl()

Returns the URL of the HTTP request.

resetback to summary
public void reset()

Implements com.badlogic.gdx.utils.Pool.Poolable.reset.

Doc from com.badlogic.gdx.utils.Pool.Poolable.reset.

Resets the object for reuse. Object references should be nulled and fields may be set to default values.

Annotations
@Override
setContentback to summary
public void setContent(String content)

Sets the content to be used in the HTTP request.

Parameters
content:String

A string encoded in the corresponding Content-Encoding set in the headers, with the data to send with the HTTP request. For example, in case of HTTP GET, the content is used as the query string of the GET while on a HTTP POST it is used to send the POST data.

setContentback to summary
public void setContent(InputStream contentStream, long contentLength)

Sets the content as a stream to be used for a POST for example, to transmit custom data.

Parameters
contentStream:InputStream

The stream with the content data.

setFollowRedirectsback to summary
public void setFollowRedirects(boolean followRedirects) throws IllegalArgumentException

Sets whether 301 and 302 redirects are followed. By default true. Can't be changed in the GWT backend because this uses XmlHttpRequests which always redirect.

Parameters
followRedirects:boolean

whether to follow redirects.

Exceptions
IllegalArgumentException:
if redirection is disabled on the GWT backend.
setHeaderback to summary
public void setHeader(String name, String value)

Sets a header to this HTTP request, see HttpRequestHeader.

Parameters
name:String

the name of the header.

value:String

the value of the header.

setIncludeCredentialsback to summary
public void setIncludeCredentials(boolean includeCredentials)

Sets whether a cross-origin request will include credentials. Only used on GWT backend to allow cross-origin requests to include credentials such as cookies, authorization headers, etc...

setMethodback to summary
public void setMethod(String httpMethod)

Sets the HTTP method of the HttpRequest.

setTimeOutback to summary
public void setTimeOut(int timeOut)

Sets the time to wait for the HTTP request to be processed, use 0 block until it is done. The timeout is used for both the timeout when establishing TCP connection, and the timeout until the first byte of data is received.

Parameters
timeOut:int

the number of milliseconds to wait before giving up, 0 or negative to block until the operation is done

setUrlback to summary
public void setUrl(String url)

Sets the URL of the HTTP request.

Parameters
url:String

The URL to set.

com.badlogic.gdx back to summary

public Interface Net.HttpResponse

Known Direct Implementers
com.badlogic.gdx.net.NetJavaImpl.HttpClientResponse

HTTP response interface with methods to get the response data as a byte[], a String or an InputStream.

Method Summary

Modifier and TypeMethod and Description
public String
getHeader(String name)

Returns the value of the header with the given name as a String, or null if the header is not set.

public Map<String, List<String>>
getHeaders()

Returns a Map of the headers.

public byte[]

Returns:

the result as a byte[] or null in case of a timeout or if the operation was canceled/terminated abnormally. The timeout is specified when creating the HTTP request, with HttpRequest#setTimeOut(int)
getResult
()

Returns the data of the HTTP response as a byte[].

public InputStream

Returns:

An InputStream with the HttpResponse data.
getResultAsStream
()

Returns the data of the HTTP response as an InputStream.

public String

Returns:

the result as a string or null in case of a timeout or if the operation was canceled/terminated abnormally. The timeout is specified when creating the HTTP request, with HttpRequest#setTimeOut(int)
getResultAsString
()

Returns the data of the HTTP response as a String.

public HttpStatus
getStatus()

Returns the HttpStatus containing the statusCode of the HTTP response.

Method Detail

getHeaderback to summary
public String getHeader(String name)

Returns the value of the header with the given name as a String, or null if the header is not set. See HttpResponseHeader.

getHeadersback to summary
public Map<String, List<String>> getHeaders()

Returns a Map of the headers. The keys are Strings that represent the header name. Each values is a List of Strings that represent the corresponding header values. See HttpResponseHeader.

getResultback to summary
public byte[] getResult()

Returns the data of the HTTP response as a byte[].

Note

This method may only be called once per response.

Returns:byte[]

the result as a byte[] or null in case of a timeout or if the operation was canceled/terminated abnormally. The timeout is specified when creating the HTTP request, with HttpRequest#setTimeOut(int)

getResultAsStreamback to summary
public InputStream getResultAsStream()

Returns the data of the HTTP response as an InputStream.

Warning

Do not store a reference to this InputStream outside of HttpResponseListener#handleHttpResponse(HttpResponse). The underlying HTTP connection will be closed after that callback finishes executing. Reading from the InputStream after it's connection has been closed will lead to exception.

Returns:InputStream

An InputStream with the HttpResponse data.

getResultAsStringback to summary
public String getResultAsString()

Returns the data of the HTTP response as a String.

Note

This method may only be called once per response.

Returns:String

the result as a string or null in case of a timeout or if the operation was canceled/terminated abnormally. The timeout is specified when creating the HTTP request, with HttpRequest#setTimeOut(int)

getStatusback to summary
public HttpStatus getStatus()

Returns the HttpStatus containing the statusCode of the HTTP response.

com.badlogic.gdx back to summary

public Interface Net.HttpResponseListener


Listener to be able to do custom logic once the HttpResponse is ready to be processed, register it with Net#sendHttpRequest(HttpRequest, HttpResponseListener).

Method Summary

Modifier and TypeMethod and Description
public void
public void
failed(Throwable
If the HTTP request failed because an Exception, t encapsulates it to give more information.
t
)

Called if the HttpRequest failed because an exception when processing the HTTP request, could be a timeout any other reason (not an HTTP error).

public void
handleHttpResponse(Net.HttpResponse
The HttpResponse with the HTTP response values.
httpResponse
)

Called when the HttpRequest has been processed and there is a HttpResponse ready.

Method Detail

cancelledback to summary
public void cancelled()
failedback to summary
public void failed(Throwable t)

Called if the HttpRequest failed because an exception when processing the HTTP request, could be a timeout any other reason (not an HTTP error).

Parameters
t:Throwable

If the HTTP request failed because an Exception, t encapsulates it to give more information.

handleHttpResponseback to summary
public void handleHttpResponse(Net.HttpResponse httpResponse)

Called when the HttpRequest has been processed and there is a HttpResponse ready. Passing data to the rendering thread should be done using Application#postRunnable(java.lang.Runnable runnable) HttpResponse contains the HttpStatus and should be used to determine if the request was successful or not (see more info at HttpStatus#getStatusCode()). For example:

 HttpResponseListener listener = new HttpResponseListener() {
 	public void handleHttpResponse (HttpResponse httpResponse) {
 		HttpStatus status = httpResponse.getStatus();
 		if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
 			// it was successful
 		} else {
 			// do something else
 		}
 	}
 }
Parameters
httpResponse:Net.HttpResponse

The HttpResponse with the HTTP response values.

com.badlogic.gdx back to summary

public final Enum Net.Protocol

extends Enum<Net.Protocol>
Class Inheritance

Protocol used by Net#newServerSocket(Protocol, int, ServerSocketHints) and Net#newClientSocket(Protocol, String, int, SocketHints).
Author
mzechner

Field Summary

Modifier and TypeField and Description
public static final Net.Protocol

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static Net.Protocol
public static Net.Protocol[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

TCPback to summary
public static final Net.Protocol TCP

Constructor Detail

Protocolback to summary
private Protocol()

Method Detail

valueOfback to summary
public static Net.Protocol valueOf(String name)
valuesback to summary
public static Net.Protocol[] values()