我的项目包含一个电话Network.SendLocation();
和以下类:
package com.example.getcurrentlocation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Build;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.util.Log;
public class Networking{
public void SendLocation(){
if (Build.VERSION.SDK_INT>= 10) {
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
}
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080/BW/Test.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
出于某种原因,我无法从通话中获得任何数据(同样适用于呼叫&#34; http://www.google.com&#34;)。同样,php从不执行任何操作,所以它根本就没有命中它。我无法弄清楚它为什么不起作用的原因。在整个电话会议之前和之后,我都用烤面包进行了测试。
答案 0 :(得分:1)
在Android中您需要连接本地服务器意味着您需要使用“http://10.0.2.2
”或“http://YOUR SERVER IP
”而不是“http://localhost:8080
”
答案 1 :(得分:0)
您的代码看起来正确,这是我的工作代码。
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
HttpResponse response = client.execute(httppost);
HttpEntity httpEntity = response.getEntity();
String state = EntityUtils.toString(httpEntity);
Log.i("henry", "state = "+state);
并确保你的php必须回应一些东西
<?PHP
echo $_POST['id'];
?>