This is somewhat what I am doing now. I use the KryoNet library also created by Nathan of LibGDX. I have a KryoNet server that my LibGDX app connects to and that server uses the jdbc to connect to a MySQL server locally. So actually without webrequests since my server is local to the DB.
Having a server between the database and your clients is not really necessary though. But I want multiplayer game mechanics that need to be handled on the server. And a TCP connection is a lot faster then webrequests.
Now for your actual question, if you want to use webrequests to run a php script for working with your database then look at the following code.
builder = new HttpRequestBuilder();
request = builder.newRequest().method(Net.HttpMethods.GET).url("http://yourdomain.com/script.php").build();
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
final long start = System.nanoTime(); //for checking the time until response
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getStatus().getStatusCode());
Gdx.app.log("WebRequest", "HTTP Response code: " + httpResponse.getResultAsString());
Gdx.app.log("WebRequest", "Response time: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
@Override
public void failed(Throwable t) {
Gdx.app.log("WebRequest", "HTTP request failed");
}
@Override
public void cancelled() {
Gdx.app.log("WebRequest", "HTTP request cancelled");
}
});
You can also send back XML and HTML if you supply the content-type in the header. Then just use your favorite parser to parse the data in your app. You can just grab it within the listeners httpResponse.getResultAsString() or httpResponse.getResultAsStream() if you like to work with a stream.
This is some php I wrote to receive XML when I wanted the same as you, then I switched over to the client -> server -> database architecture.
<?php
$link = mysqli_connect("127.0.0.1", "root", "", "test");
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><mysql></mysql>");
if (!$link)
{
$xml->addChild("error", "Error: Unable to connect to MySQL.");
$xml->addChild("error", "Debugging errno: " . mysqli_connect_errno());
$xml->addChild("error", "Debugging error: " . mysqli_connect_error());
exit;
}
$xml->addChild("success", "Success: A proper connection to MySQL was made!");
$xml->addChild("success", "Host information: " . mysqli_get_host_info($link));
//To send the xml data back:
print($xml->asXML());
mysqli_close($link);
?>
Take note that you do have to change the header to receive xml data in your app.
jdbcis a java library to do exactly the same. I'm not sure however if it's compatible with platforms other then desktop. I'm using that on the server side of my wip game. \$\endgroup\$