我是一个有用的助手,可以为您进行翻译。
我正在尝试将JSON发送到PHP并存储所发送的数据,但我无法使其正常工作。
我的Android代码:
我正在尝试将JSON发送到PHP并存储所发送的数据,但我无法使其正常工作。
我的Android代码:
public void sendToServer(String txt) throws JSONException{
String path = "http://10.0.0.6:8888/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("text", txt);
Log.i("jason Object", json.toString()); //This print the data perfectly
post.setHeader("json", json.toString());
post.setHeader("Accept", "application/json");
Log.i("Done", "DONE 1");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
Log.i("Done", "DONE 2");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myjson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("Done", "DONE 3");
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();
}
}
和我的php代码
<?php
$decoded = json_decode(stripslashes($_POST['myjson']));
if($decoded)
$con = mysql_connect('localhost','root','root')
or die('Cannot connect to the DB');
mysql_select_db('deaf',$con);
mysql_query("INSERT INTO text
VALUES ('".$decoded->{'text'}"')");
mysql_close($con);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
else
echo "error";
?>
插入语句无法正常工作,我已经花了数小时尝试修复,但都没有成功。请帮助我,谢谢。
in
变量中得到了什么?用if {} else {}
替换你的模板化if
。它只适用于1行代码,而你在那个if中有10行。这是行不通的。 - Hamza Waqas