我正在尝试将从ConnectionRequest获取的响应数据写入Codename one中的本地Json文件,但我不知道从哪里开始...任何人对此都有任何线索所以请发表您的答案。
答案 0 :(得分:1)
以下是使用ConnectionRequest.setDestinationFile()
将内容下载到本地文件的示例。
private static boolean downloadUrlTo(String url, String fileName, boolean showProgress, boolean background, boolean storage, ActionListener callback) {
ConnectionRequest cr = new ConnectionRequest();
cr.setPost(false);
cr.setFailSilently(true);
cr.setDuplicateSupported(true);
cr.setUrl(url);
if(callback != null) {
cr.addResponseListener(callback);
}
if(storage) {
cr.setDestinationStorage(fileName);
} else {
cr.setDestinationFile(fileName);
}
if(background) {
NetworkManager.getInstance().addToQueue(cr);
return true;
}
if(showProgress) {
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(cr);
d.dispose();
} else {
NetworkManager.getInstance().addToQueueAndWait(cr);
}
return cr.getResponseCode() == 200;
}
答案 1 :(得分:1)
以下代码将从服务器获取JSON对象并将其保存到本地文件。
{{1}}
答案 2 :(得分:0)
我不确定你真正想做什么,但是为了处理JSON对象,你可能想尝试json.org提供的框架:https://mvnrepository.com/artifact/org.json/json 有了这个,您可以将响应转换为JSON对象,然后从该对象中提取数据。
这是HTTP-POST请求的示例:
public class PostTest {
public static void main(String[] args) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//This section is for creating and executing the POST-Request
URIBuilder uriBuilder = new URIBuilder("http://www.example.com/");
URI uri = uriBuilder.build();
HttpPost request = new HttpPost(uri);
HttpResponse response = httpclient.execute(request);
//This section converts the response into a HttpEntity
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
//This converts the HttpEntity into a JSON Object
if (entity != null) {
String responseString = EntityUtils.toString(entity);
JSONObject responseObject = responseString.getJSONObject();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
如果请求成功,您现在可以从responseObject
中提取数据,如下所示:
String fieldContent = responseObject.getString("fieldName");
System.out.println("Example field: " + fieldContent);
其中fieldName
表示responseObject
我意识到这可能不是您正在寻找的确切方案,但我希望它可能会给您一个想法。