这是我的代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("dropbox link to php code");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
System.out.println(is);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("1 " + result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
}
}
catch (JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
HTTPPost中的链接是Dropbox上PHP代码的下载链接。该代码如下所示:
<?php
mysql_connect("host","username","password");
mysql_select_db("1487057_test");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
问题是HTTP代码似乎没有“执行”PHP代码。当我打印输入流时,我只回到PHP代码的前两行。 JSON日志似乎根本不打印。有谁看到了什么问题?
答案 0 :(得分:1)
如果你有来自ftp服务器的json数据,它将正常工作,因为你 使用Dropbox for php file,你需要确保它有效 如果它工作正常,建议你先在浏览器上测试服务 可以继续使用code.possibly设置ftp而不是Dropbox as 文件服务器。
答案 1 :(得分:0)
将您的PHP修改为:
<?php
$sql = "SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'";
mysql_query("set names utf8");
$result = mysql_query($sql);
while ($e = mysql_fetch_assoc($result)) {
$output[]=$e;
}
print(json_encode($output));
mysql_close($dbhost);
&GT;