如何使用libgdx HttpRequest和HttpResponseListener从网页保存图像?

时间:2014-07-15 10:19:54

标签: android libgdx

我目前使用这些方法的代码在这里,可以正常工作以获取文本。如何修改此项以将图像保存到文件系统?

public static class URLResponseListener implements HttpResponseListener {
    public void handleHttpResponse(HttpResponse httpResponse) {
        statusCode = httpResponse.getStatus().getStatusCode();
        urlResults = httpResponse.getResultAsString();
    }

    public void failed(Throwable t) {
        statusCode = Constants.CONNECTION_FAILED;
        urlResults = null;
    }

    public String getLastResponse() {
        return urlResults;
    }

    @Override
    public void cancelled() {
        urlResults = null;          
    }
}

private void getUrlData() {
    httpGet = new HttpRequest(HttpMethods.GET);
    httpGet.setUrl(Constants.DATA_URL);
    responseListener = new URLResponseListener();
    Gdx.net.sendHttpRequest (httpGet, responseListener);
}

在我的渲染方法中,我有以下检查http连接何时完成

        if (statusCode >= 200 && statusCode <= 300 && null != urlResults) {
            try {
            // process urlResults text
            } catch (Exception e) {
                e.printStackTrace();
            }
            statusCode = 0;
            urlResults = null;

        }
        if (statusCode == Constants.RETRY_CONNECTION || statusCode == Constants.CONNECTION_FAILED) {
            statusCode = 0;
            getUrlData();
        }

1 个答案:

答案 0 :(得分:0)

在libgdx论坛上得到了BurningHand的答案

@Override
public void handleHttpResponse (HttpResponse httpResponse) {
    if (httpResponse.getStatus().getStatusCode() == 200) {
        Gdx.files.external("downloaded.img").write(httpResponse.getResultAsStream(), false);
    }
}