How send data to website by using android app

2019-01-11 12:20发布

问题:

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()

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.

回答1:

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



回答2:

Use the following code

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();
}


回答3:

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);
}

}



回答4:

Here is an code snippet , hoping it will help you.

1)An function which carries the http get service

   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) An Class which extends 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) Inside your onCreate method

     @Override
public void onCreate(Bundle savedInstanceState) {

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



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

        new HTTPdemo().execute("");
    }

   }

The code snippet provided by me works in the following way,

1)Android device send the URL+data to server

2)Server [say PHP used] receive the data and gives an acknowledgement

Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is

  • Server needs to receive the data
  • Implement an functionality at server side
  • That functionality [web service] will be invoked whenever android will push the URL+data
  • Once you have the data ,manipulated it as you want