gpt4 book ai didi

php - 在代号一中使用 webservices 时如何解析 null

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:39 25 4
gpt4 key购买 nike

我在 php 中调用数据库中的数据,并使用 Web 服务将数据传递给代号 one。如果我将我的 URL 指向一个 JSON 文件,我能够获取我的记录,但是当我将它更改为 php 并使用 JSON 对页面进行编码时,我得到的是空值。

在 Codename one 中使用 Web 服务时如何解析空结果?

这是我在代号一中调用的 php 代码

<?php 
/* require the user as the parameter */
//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
/*soak in the passed variable or set our own*/
//$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
//$user_id = intval($_GET['user']); //no default

/* connect to the db */
$link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
mysql_select_db('test',$link) or die('Cannot select the DB');

/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM bugs";
$result = mysql_query($query,$link) or die('Errant query: '.$query);

/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('respons'=>$post);
}
}

/* output in necessary format */
if($format == 'json') {
// header('Content-type: application/json');
echo json_encode(array('respons'=>$posts));
}


/* disconnect from the db */
@mysql_close($link);
}

这是我的代号一代码

private static final String URL = "http://localhost/webpin/webservice1.php?user=1&format=json";
showpix.addActionListener((e)->{
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void handleException(Exception ex) {
//handle error
}
};
req.setUrl(URL);
req.setPost(true);
req.setHttpMethod("GET"); //Change to GET if necessary
req.setDuplicateSupported(true);
req.addArgument("user", mypin.getText());
//req.addArgument("argumentToSendThroughPostOrGet2", "value2");
NetworkManager.getInstance().addToQueueAndWait(req);

if (req.getResponseCode() == 200) {
Map<String, Object> out = new HashMap<>();
Display.getInstance().invokeAndBlock(() -> {
JSONParser p = new JSONParser();
try (InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(req.getResponseData()))) {
out.putAll(p.parseJSON(r));
} catch (IOException ex) {
//handle error
}
});
if (!out.isEmpty()) {
List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("respons");
for (Object response : responses) {
Map res = (Map) response;
//Object hk = res.get("id");
System.out.println(res.get("id"));
//if(hk.equals("I was returned")){
Dialog.show("ok",res.get("id") + "", "ok", "ok");
//}
//System.out.println(res.get("key"));
}
} else {
//handle error
}
} else {
//handle error
}
//req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
});

当我使用提供的解决方案调试我的代码时,我收到以下错误代码:

java.lang.IllegalStateException: Request method (post/get) can't be modified once arguments have been assigned to the request
Rendering frame took too long 391 milliseconds
at com.codename1.io.ConnectionRequest.setPost(ConnectionRequest.java:1046)
at com.mycompany.myapp.MyApplication.lambda$start$1(MyApplication.java:293)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:349)
at com.codename1.ui.Button.fireActionEvent(Button.java:411)
at com.codename1.ui.Button.released(Button.java:442)
at com.codename1.ui.Button.pointerReleased(Button.java:530)
at com.codename1.ui.Form.pointerReleased(Form.java:2623)
at com.codename1.ui.Form.pointerReleased(Form.java:2559)
at com.codename1.ui.Component.pointerReleased(Component.java:3223)
at com.codename1.ui.Display.handleEvent(Display.java:2022)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1067)
at com.codename1.ui.Display.mainEDTLoop(Display.java:996)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

这是代码:

      showpix.addActionListener((e)->{
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void handleException(Exception ex) {
//handle error
}
};
req.setUrl(DESTINATION_URL);
req.setPost(true);
req.setHttpMethod("GET"); //Change to GET if necessary
req.setDuplicateSupported(true);
//req.addArgument("user", mypin.getText());

req.addArgument("user", mypin.getText());
req.addArgument("format", "json");
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);

if (req.getResponseCode() == 200) {
Map<String, Object> out = new HashMap<>();
Display.getInstance().invokeAndBlock(() -> {
JSONParser p = new JSONParser();
try (InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(req.getResponseData()))) {
out.putAll(p.parseJSON(r));
} catch (IOException ex) {
//handle error
}
});


if (!out.isEmpty()) {
List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("response");
for (Object response : responses) {
Map res = (Map) response;

// Object hk = res.get("id");
System.out.println(res.get("id"));
// if(hk.equals("I was returned")){
// Dialog.show("ok",res.get("pin")+ "", "ok", "ok");


// }

System.out.println(res.get("id"));



}
} else {
//handle error
}
} else {
//handle error
}


});

另一个错误代码:

警告:Apple 将不再接受来自您尝试连接到的应用程序的 http URL 连接 http://localhost/webpin/webservice1.php?user=1&format=json要了解更多信息,请查看 https://www.codenameone.com/blog/ios-http-urls.html[invokeAndBlock1] 0:0:0,0 - 代号一修订版:375ed2c938445450f0983f0d18235f61e793a7ee2004

[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 1 column: 12 buffer: E
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 2 column: 3 buffer: E
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 4 column: 12 buffer: Eede
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 4 column: 13 buffer: Eede
[invokeAndBlock1] 0:0:0,0 - Exception: java.lang.ArrayIndexOutOfBoundsException - -1
java.lang.ArrayIndexOutOfBoundsException: -1
[invokeAndBlock1] 0:0:0,16 - Exception during JSON parsing at row: 4 column: 33 buffer: EedeeContent-Type
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at com.codename1.io.JSONParser.isStackHash(JSONParser.java:449)
at com.codename1.io.JSONParser.stringToken(JSONParser.java:527)
at com.codename1.io.JSONParser.parse(JSONParser.java:164)
at com.codename1.io.JSONParser.parseJSON(JSONParser.java:427)
at com.mycompany.myapp.MyApplication.lambda$null$0(MyApplication.java:302)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:103)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:140)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

最佳答案

我注意到的第一件事是您调用了 NetworkManager.getInstance().addToQueueAndWait(req); 两次。

第二件事是,如果您在 php 中使用 $_GET 方法,则应将 req.setPost(true); 更改为 req.setPost(false);

第三,从您的 URL 中删除 "?" 和后面的所有内容,无论您想要传递什么,都应该通过下面添加:

网址:

private static final String URL = "http://localhost/webpin/webservice1.php";

参数:

req.addArgument("format", "json");
req.addArgument("user", mypin.getText());

在 php 端,在浏览器中运行您的代码以确保您的代码中没有错误 请务必取消注释 header。请参阅以下对您的代码的细微更改:

$posts = array();
$row = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts["response"][] = $post;
}
$row = array("respons" => $posts["response"], "code" => 200, "message" => "success");
} else {
$row = array("code" => 101, "message" => "No data was returned");
}

/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode($row, JSON_PRETTY_PRINT);
}

关于php - 在代号一中使用 webservices 时如何解析 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40146488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com