有人可以提供上述解决方案吗?
现在,我要做的就是向我的服务器发送JSON请求(例如:{picture:jpg,color:green}),让PHP访问数据库,然后从服务器的数据库返回文件名(然后获取android下载文件- 不是问题)
谁能首先建议一个Android框架来帮助我。-将JSON发布到服务器上的php文件
其次是将JSON转换为php可读格式的php脚本(访问数据库也不是问题,但我无法将JSON转换为对象然后与数据库匹配)
谢谢
编辑
感谢下面的链接,但我并不是出于懒惰而问,我似乎无法发送JSON字符串并获得正确答案,这让我很烦。
因此,让我展示一些代码,找出为什么我认为应该发生的事情没有发生:
GET URL(使用GET,以便我可以显示工作状态)
http://example.com/process/json.php?service=GOOGLE <?php // decode JSON string to PHP object $decoded = json_decode($_GET['json']); // I'm not sure of which of the below should work but i've tried both. $myService = $decoded->service; //$service should equal: GOOGLE $myService = $decoded->{'service'}; //$service should equal: GOOGLE // but the result is always $myService = null - why? ?>
好的,我有PHP。下面检索POST ed数据并返回服务
<?php $data = file_get_contents('php://input'); $json = json_decode($data); $service = $json->{'service'}; print $service; ?>
和Android代码:
在onCreate()中
path = "http://example.com/process/json.php"; HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout // Limit HttpResponse response; JSONObject json = new JSONObject(); try { HttpPost post = new HttpPost(path); json.put("service", "GOOGLE"); Log.i("jason Object", json.toString()); post.setHeader("json", json.toString()); StringEntity se = new StringEntity(json.toString()); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = client.execute(post); /* Checking response */ if (response != null) { InputStream in = response.getEntity().getContent(); // Get the // data in // the // entity String a = convertStreamToString(in); Log.i("Read from Server", a); } } catch (Exception e) { e.printStackTrace(); }
还有你想去的地方
private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }