如何使用 android 应用程序将数据发送到网站

Posted

技术标签:

【中文标题】如何使用 android 应用程序将数据发送到网站【英文标题】:How send data to website by using android app 【发布时间】:2013-04-25 06:57:04 【问题描述】:

我正在尝试向我的网站发送一些数据。单击按钮时,需要向网站发送数据

但我在运行程序时遇到了一些错误

当我单击按钮时,此消息显示“不幸的是应用程序已停止”,然后它退出我的应用程序。

 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 代码。

<?php

//code to reverse the string

$reversed = strrev($_POST["action"]);

echo $reversed;

?>

我还获得了在我的应用中使用互联网的许可。

【问题讨论】:

你没有提到你得到的错误。 你有什么有用的吗?如果是这样,请发布以帮助大家。谢谢! 【参考方案1】:

android 3.x 起,您无法在主线程中执行网络操作。您需要使用 AsyncTask 或单独的线程来调用您的 postData 方法。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

【讨论】:

谢谢,请您进一步解释一下,因为我是android开发的新手 ***.com/a/9671602/527759 developer.android.com/reference/android/os/AsyncTask.html【参考方案2】:

这里是一个代码 sn-p ,希望对你有帮助。

1)带有http get服务的函数

   private String SendDataFromAndroidDevice() 
    String result = "";

    try 
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet getMethod = new HttpGet("your url + data appended");

        BufferedReader in = null;
        BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
                .execute(getMethod);
        in = new BufferedReader(new InputStreamReader(httpResponse
                .getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) 
            sb.append(line);
        
        in.close();
        result = sb.toString(); 


     catch (Exception e) 
        e.printStackTrace();
    
    return result;

2) 扩展 AsyncTask 的类

   private class HTTPdemo extends
        AsyncTask<String, Void, String> 

    @Override
    protected void onPreExecute() 

    @Override
    protected String doInBackground(String... params) 
        String result = SendDataFromAndroidDevice();
        return result;
    

    @Override
    protected void onProgressUpdate(Void... values) 

    @Override
    protected void onPostExecute(String result) 

        if (result != null && !result.equals("")) 
            try 
                JSONObject resObject = new JSONObject(result);

                 catch (Exception e) 
                e.printStackTrace();
            
        
    

3) 在你的 onCreate 方法中

     @Override
public void onCreate(Bundle savedInstanceState) 

    super.onCreate(savedInstanceState);
    setContentView("your layout");



    if ("check here where network/internet is avaliable") 

        new HTTPdemo().execute("");
    

   

我提供的代码sn-p的工作方式如下,

1)Android设备发送URL+数据到服务器

2)服务器 [说使用了 PHP] 接收数据并给出确认

现在提供给您应该在客户端(Android)编写的代码,在服务器接收该数据的后面部分是

服务器需要接收数据 在服务器端实现功能 只要 android 推送 URL+数据,就会调用该功能 [web 服务] 获得数据后,根据需要对其进行操作

【讨论】:

【参考方案3】:

使用以下代码

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yoursite.com/index.php");

String MyName = toPost; 

try 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("action", MyName));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);

    InputStream is = response.getEntity().getContent();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    result = br.readLine();
    //This is the response from a php application
    String reverseString = result;
    Toast.makeText(this, "result" + reverseString, Toast.LENGTH_LONG).show();

catch(Exception e)

    Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();

【讨论】:

【参考方案4】:
i hope this help u alloott
package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity 

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button but=(Button)findViewById(R.id.button1);
    but.setOnClickListener(new View.OnClickListener() 

        @Override
        public void onClick(View v) 
            // TODO Auto-generated method stub
            postData();

        
    );




@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

public void postData() 
    // Create a new HttpClient and Post Header
    class ss extends AsyncTask<Void, Void, String>
    

    @Override
    protected String doInBackground(Void... params) 
        // TODO Auto-generated method stub
        HttpClient httpclient = new DefaultHttpClient();
        String result = null;
        HttpPost httppost = new HttpPost("http://www.techdoo.com/test.php");

        try 
        

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("action", "fadeel"));

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        result = br.readLine();
        //This is the response from a php application
        String reverseString = result;
        EditText edit1=(EditText)findViewById(R.id.editText1);
        edit1.setText(result);
        //  Toast.makeText(this, "result" + reverseString, Toast.LENGTH_LONG).show();
        
        catch(Exception e)
        
        //Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
        
        return result;
    
    @Override
        protected void onPostExecute(String result) 
            // TODO Auto-generated method stub
        if(result==null)
        
            Toast.makeText(getApplicationContext(), "not ok", Toast.LENGTH_LONG).show();
        
        else
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();

            super.onPostExecute(result);
        

    
    ss s=new ss();
    s.execute(null,null,null);

【讨论】:

仅供参考 - 在我的代码中尝试了 postData() 方法,截至 2015-06-14 方法和 HttpResponse、HttpClient 和 NameValuePair 已弃用。我无法让它工作,但这仅仅是因为我忘记了 android.permission.INTERNET 的清单权限添加。此代码确实有效。

以上是关于如何使用 android 应用程序将数据发送到网站的主要内容,如果未能解决你的问题,请参考以下文章

如何将数据从服务器发送到Android?

如何将 Web 仪表板与 Android 应用程序连接并发送数据

如何将带有位置的数据实时发送到服务器?我做对了吗?

如何将 Flutter Web 应用程序嵌入网站并通过网站将数据发送到 Flutter Web 应用程序

使用 android 应用程序的输入数据自动填充网站表单

Android:如何在不使用 PHP 或任何网络服务的情况下将数据发送到远程数据库?