2017-03-21 84 views
2

我想写从ConnectionRequest获取的响应数据到Codename中的本地Json文件,但我不知道从哪里开始......有人对此有任何线索,所以请张贴您的回答。ConnectionRequest响应处理

+0

'在Codename one'中 - 你是什么意思? – Divers

+0

看看PropertyCross演示 – Diamond

+0

@Divers https://www.codenameone.com/ –

回答

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中使用的变量的名称

我意识到这可能不是您正在寻找的确切场景因为,但我希望它可以给你一个想法。

+0

查看https://www.codenameone.com/ –

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; 
    } 

See full source

1

下面的代码会从服务器获取一个JSON对象,并将其保存到本地文件。

String fspath = FileSystemStorage.getInstance().getAppHomePath(); 
String url = "http://example.com/getSomeJSON.php"; 

ConnectionRequest cr = new ConnectionRequest(url, false); 
cr.setDestinationFile(fspath + "mylocalfile.json"); 
NetworkManager.getInstance().addToQueue(cr);