我使用这个论坛很长时间了,首先,我想说谢谢你帮助我很多次。这是我第一次找不到答案,这让我很疯狂......
我正在尝试编写一个超级简单的应用程序,它从/向数据库获取/发布数据。问题是,我无法发布数据(获取很好)。我正在使用一个 php 文件,它应该从 Android 设备获取数据,并将其发送到数据库。首先,我无法将其发布到我的 php 文件中。我已经尝试了所有(我知道)。
PHP文件-
$test=$_POST['v']; print $_POST['v'];
Java文件-
public void postData() 抛出 ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.myweb.coom/test.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("v", "123"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
httpclient.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
当我放 Log.* 时,它告诉我一切都很好。似乎PHP没有得到任何数据......
EDITING ASYNTASK----- public class Upload extends AsyncTask{
@Override
protected String doInBackground(String... params) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//
String url = "http://my WAMP server/test.php"+
"json={\"UserName\":1,\"FullName\":2}";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = "gr8 Success";
Log.i("Read from server", result);
}
} catch (Throwable t) {
Log.e("Request failed: " ,"ERR"+ t.toString());
}
}
}
主要活动-
public void postData(View v) { //starts on button click
if(upload!=null){
if(upload.getStatus()!= AsyncTask.Status.FINISHED){
Log.d("postData","no need to start AsyncTask");
return;
}
}
upload= new Upload();
upload.execute();
Log.i("Async", "Starting...");
}
PHP- $json=$_GET ['json']; $obj = json_decode($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));