我在php中调用数据库中的数据,并使用Webservices将数据传递给代号。如果我将我的URL指向JSON文件,我就可以获取我的记录,但是当我将其更改为php并使用JSON对页面进行编码时,我将变为空。
如何在Codename中使用Webservices时解决null结果?
这是我用代号
调用的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://localhost/webpin/webservice1.php?user=1&format=json的应用程序的http URL连接,以了解更多信息https://www.codenameone.com/blog/ios-http-urls.html [invokeAndBlock1] 0:0:0,0 - Codename One修订版:375ed2c938445450f0983f0d18235f61e793a7ee 2004年
[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)
答案 0 :(得分:2)
我注意到的第一件事是你两次打电话给NetworkManager.getInstance().addToQueueAndWait(req);
。
第二件事是,如果你在php中使用$ _GET方法,你应该将req.setPost(true);
更改为req.setPost(false);
。
第三,删除&#34;?&#34; 以及网址之后的所有内容,无论您想传递什么,都应通过以下内容添加:
<强> 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);
}