import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button btn = (Button) findViewById(R.id.btnInsert);
EditText editText = (EditText) findViewById(R.id.editText);
final String value = editText.getText().toString();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("name", value);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost("http://www.myurl.com/WebserviceInsert2.php");
StringEntity se = new StringEntity(jsonobj.toString());
Log.d("jsonobj is :>", String.valueOf(jsonobj));
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity()); // {"code":1}
} catch (Exception e) {
e.printStackTrace();
Log.i("Parse Exception", e + "");
}
Log.d("Response Text is : ", responseText);
JSONObject json = new JSONObject(responseText);
int code = json.getInt("code");
if (code == 1)
Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.d("Error :>", String.valueOf(e));
}
}
});
}
}
PHP Code:
<?php
include("include/config.php");
$name=$_POST["name"];
//echo $name;
$flag['code']=0;
if($result=mysql_query("INSERT INTO test (name) VALUES ('".$name."')"))
{
$flag['code']=1;
}
print(json_encode($flag));
$obj->close();
?>
數據庫表字段「name」爲空。插入查詢成功觸發,但..數據未插入到表中。無法從Android中的JSON中將數據導入到PHP webservice中
我認爲PHP文件沒有得到正確的'名稱'參數從POST應用程序的Android應用程序(JSON)發送的方法。