从Android应用程序我想发送一些数据。该数据应显示在网站上。目前我正在使用XAMPP在localhost中尝试。
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new NetworkOperation().execute();
//Toast.makeText(getBaseContext(), "response", Toast.LENGTH_LONG).show();
}
});
}
另一个班级
public class NetworkOperation extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.0.104/Project/script.php");
try{
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("id","somevalue"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", (response.getEntity()).toString());
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("clientprotocolexception");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOexception");
e.printStackTrace();
}finally {
httpClient.getConnectionManager().shutdown();
}
return null;
}
包含在清单中
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我有php脚本文件如下
<?php
$error = 'Not received';
$result = (isset($_POST['id']) ? $_POST['id'] : $error);
echo $result;
&GT;
答案 0 :(得分:0)
您正在发送HTTP POST
请求,但不会处理它返回的数据。这将是一个关于如何等待服务器端响应的示例,我试图评论相关部分,以便它易于理解。
HttpResponse response = null;
try {
// Fill in the POST pair you want to sent to the server
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mykey", "myvalue"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Send the request
response = httpclient.execute(httppost);
}
catch (final ClientProtocolException e) { ... }
catch (final IOException e) { ... }
// Now you have to process the response
InputStream ips;
try {
ips = response.getEntity().getContent();
final BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if ((s == null) || (s.length() == 0))
break;
sb.append(s);
}
buf.close();
ips.close();
Log.d("JSONResponse", "My response from the server is: " + sb.toString());
}
catch (IllegalStateException e1) { }
catch (IOException e1) { }
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
try { throw new Exception(response.getStatusLine().getReasonPhrase()); }
catch (final Exception e) { e.printStackTrace(); }
}