How to send data to a website using httpPost, app

2019-02-28 07:42发布

This question already has an answer here:

Currently I am working on a project. I need to send some data from my android app to a webserver. But when I touched the send button the app crashes.

Here is my .java file

package com.androidexample.httppostexample;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class HttpPostExample extends Activity {

    Button sendButton;

    EditText msgTextField;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // load the layout
        setContentView(R.layout.activity_http_post_example);        

        // make message text field object
        msgTextField = (EditText) findViewById(R.id.msgTextField);
        // make send button object
        sendButton = (Button) findViewById(R.id.sendButton);

    }

    // this is the function that gets called when you click the button
    public void send(View v)
    {
        // get the message from the message text box
        String msg = msgTextField.getText().toString();  

        // make sure the fields are not empty
        if (msg.length()>0)
        {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.eeecoderpages.orgfree.com/post.php");
         try {
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
           nameValuePairs.add(new BasicNameValuePair("id", "12345"));
           nameValuePairs.add(new BasicNameValuePair("message", msg));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
           httpclient.execute(httppost);
           msgTextField.setText(""); // clear text box
         } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
         } catch (IOException e) {
             // TODO Auto-generated catch block
         }

        }
        else
        {
            // display message if text fields are empty
            Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
        }

    }

}

Here is my xml gui file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:text="Message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        /> 

    <EditText
        android:id="@+id/msgTextField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:text="Send"
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="send"
        /> 

</LinearLayout>

I also add the internet permission to the manifest :

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

And in the webserver side, I used the following php script:

<?php

    // get the "message" variable from the post request
    // this is the data coming from the Android app
    $message=$_POST["message"]; 

    // specify the file where we will save the contents of the variable message
    $filename="androidmessages.html";

    // write (append) the data to the file
    file_put_contents($filename,$message."<br />",FILE_APPEND);

    // load the contents of the file to a variable
    $androidmessages=file_get_contents($filename);

    // display the contents of the variable (which has the contents of the file)
    echo $androidmessages;


    ?>

But it doesn't work. When I touched the send button the system shutdown my app. I searched a lot of solutions but non-of them works for me. Any help from any body I will be grateful!

3条回答
\"骚年 ilove
2楼-- · 2019-02-28 08:19

Networking operation on UI Main thread are not allowed.

Try following code.

public class NetRequestAsync extends AsyncTask<Void, Void, Boolean> {

    String id, msg;

    public NetRequestAsync(String id, String message) {
        this.id = id;
        this.msg = message;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://www.eeecoderpages.orgfree.com/post.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("id", id));
            nameValuePairs.add(new BasicNameValuePair("message", msg));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if(result){
            //successful request
        }else{
            //error in request response
        }
        msgTextField.setText(""); // clear text box
    }

}

To use this code,

NetRequestAsync request = new NetRequestAsync("12345","Hi");
request.execute();

Note

UI operation like updating TextView, EditText or setting image to ImageView are not allowed in doInBackground() method. You can do that in onPostExecute() or onPreExecute().

查看更多
Emotional °昔
3楼-- · 2019-02-28 08:33

It sound like you are getting NetworkOnMainThread Exception

Reason: you are performing Network Operation on Main UI Thread

Solution: use AsyncTask

查看更多
冷血范
4楼-- · 2019-02-28 08:39

You are doing a network related operation on the main ui thread. Use a thread or asynctask.

You will get NetworkOnMainThreadexception post honeycomb.

      new PostTask().execute();

AsyncTask

 class PostTask extends AsyncTask<Void,Void,Void>
 {
      @Override
      protected void doInbackground(Void... params)
      {
             // network related operation
             // do not update ui here
             // your http post here
      }
 } 

Also if you use threads or asynctask remember not to update ui in doInbackgroud.

You have this

      String msg = msgTextField.getText().toString();  
      // you can pass msg to asynctask doInbackground or to the asynctask contructor
      msgTextField.setText(""); 

Use onPreExecute and onPostExecute for ui updation.

查看更多
登录 后发表回答