如何将数据从libgdx项目发送到web



我想把json数据从libgdx移到我的web服务器上,但我不知道怎么做。下面的方法是参考libgdx的文档创建的。

private void httpPostJson(){
final Json json = new Json();
final String requestJson = json.toJson(requestObject);
Net.HttpRequest request = new Net.HttpRequest("POST");
final String url = "http://localhost:8080/data";
request.setUrl(url);
request.setContent(requestJson);
request.setHeader("Content-Type", "application/json");
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
String responseJson = httpResponse.getResultAsString();
Gson gson = new Gson();
data = gson.fromJson(responseJson, Person.class);
//'Person' is just sample class. data is class Person's object.
data.StoreData("",1);//successed to receive json data from web server.
//StoreData is just getter method.
}
@Override
public void failed(Throwable t) {
Gdx.app.log("failed!");
}
@Override
public void cancelled() {
Gdx.app.log("cancelled!");
}
});
}

可以接收从网络服务器发送的数据。但是,这种方法无法将数据发送到web服务器。你能告诉我如何将数据从libgdx项目转移到web服务器吗?

这是传输到web服务器的数据:

final String requestJson = json.toJson(requestObject);

我们使用以下代码(因为与使用gdx.net相比,您对请求有更多的控制权(,工作起来很有魅力,只是不要在主线程上执行-主体是您的JSON作为字符串

URL url = new URL(<your url>);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type",
"application/json; charset=utf-8"); 
if (body != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
os, "UTF-8"));
writer.write(body);
writer.close();
os.close();
}
conn.connect();
String s = stringFromStream(conn.getInputStream(), 4096);

方法字符串FromStream:

public static String stringFromStream(final InputStream is,
final int bufferSize) {
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
} finally {
in.close();
}
} catch (Exception ex) {
}
return out.toString();
}

最新更新