如何使用Android的应用程序将数据发送到网站 [英] How send data to website by using android app
问题描述
我想一些数据发送到我的网站。当点击该按钮时,数据需要被发送到网站
I'm trying to send some data to my website. When the button is clicked, data need to be sent to the web site
但是当我运行程序我得到了一些错误
but I got some errors when I am running the program
当我点击不幸的是应用程序已经停止,那么它退出我的申请。出现此消息的按钮
when I clicked the button this message appears "unfortunately app has stopped" then it exit my application.
public class testInput extends Activity {
Button Setbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_input_page);
Setbutton=(Button)findViewById(R.id.setbtn);
Setbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
testInput ti=new testInput();
//Create the intent
ti.postData("Sent Data");
});
}
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/index.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
这是我的PHP code。
This is my PHP code.
<?php
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
?>
我在我的应用程序得到许可也使用互联网。
I got permission also for use internet in my app.
推荐答案
由于Android 3.X您不能在主线程中执行网络操作。您需要使用的AsyncTask或单独的线程,你可以打电话给你POSTDATA方法。
Since Android 3.x you can't perform network operations in main thread. You need to use AsyncTask or separate thread where you can call your postData method.
的http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
这篇关于如何使用Android的应用程序将数据发送到网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!