我想按此顺序在同一会话中实现以下目标:
我使用以下内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
// 01 - first i get imei
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
// 02 - then i call class to post imei to php
new loadData().execute();
// 03 - on php side i use "select ... where $imei ..."
// 04 - get the results back to android
// (yes i am aware that this method is commented out, i will explain why below)
//accessWebService();
}
POST:
class loadData extends AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
String imeino = String.valueOf(IMEI);
nameValuePairs.add(new BasicNameValuePair("imeino",imeino));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://blah/contacts.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Error Send",e.toString());
}
return id;
}
}
GET
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("jsonResult: "+jsonResult);
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://blah/contacts.php" });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("contact_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("Name");
String number = jsonChildNode.optString("Number");
String username = jsonChildNode.optString("Username");
String status = jsonChildNode.optString("Status");
System.out.println("jsonResult: "+jsonResult);
System.out.println("getName: "+name);
System.out.println("getNumber: "+number);
System.out.println("getUsername: "+username);
System.out.println("getStatus: "+status);
}
} catch (JSONException e) {
System.out.println("Json Error" +e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
PHP:
<?php
include 'config.php';
$con=mysql_connect("$servername", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
//$imei = "000000000000000";
$sql = "select * from users WHERE IMEI ='$imei'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['contact_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
$f = fopen("log.txt", "w");
fwrite($f, print_r($json, true));
fclose($f);
?>
好的,这是代码的故事:
当我刚发布[new loadData().execute()
]而不是GET [accessWebService();
]时,我可以将$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
变量读作0000000000000
但当然我无法返回结果,因为accessWebService()
已被注释掉。
然而,当我取消注释accessWebService()
时,我可以将结果返回到android但是它们是null
,因为现在$imei = isset($_POST['imeino']) ? $_POST['imeino'] : '';
为空。
总结一下:
每当我调用GET方法时,我都会丢失POST变量!
答案 0 :(得分:1)
<强> PHP 强>
要支持PHP中的GET
和POST
变量,您可以使用$_REQUEST
:
$imei = isset($_REQUEST['imeino']) ? $_REQUEST['imeino'] : '';
检查参数是否已设置也是明智的,如果不是,则返回错误:
if ( empty($imei) ) {
echo json_encode( array( 'error' => 'Missing imeino parameter' ) );
return;
}
而且,非常重要的是,在将输入传递给mysql之前清理输入。这很危险:
$sql = "select * from users WHERE IMEI ='$imei'";
因为有人可能会使用contacts.php?imeino=';DROP TABLE users'
调用您的PHP脚本。 See here了解更多信息。
顺便说一下,PHP's mysql module is deprecated;我建议使用PDO。
<强>爪哇强>
访问API的GET
方法只需稍加更改即可将imeino
参数传递给PHP脚本:
public void accessWebService( String imei ) {
JsonReadTask task = new JsonReadTask();
task.execute(new String[] { "http://blah/contacts.php?imeino=" + imei });
}
而且,您需要使用IMEI致电accessWebService
。