Java 如何使用httpPost向网站发送数据,应用程序崩溃

Java 如何使用httpPost向网站发送数据,应用程序崩溃,java,php,android,http,http-post,Java,Php,Android,Http,Http Post,目前我正在做一个项目。我需要从android应用程序向Web服务器发送一些数据。但当我按下发送按钮时,应用程序崩溃了 这是我的.java文件 package com.androidexample.httppostexample; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import java.util.ArrayList; import java.util.List;

目前我正在做一个项目。我需要从android应用程序向Web服务器发送一些数据。但当我按下发送按钮时,应用程序崩溃了

这是我的.java文件

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

    }

}
package com.androidexample.httppostexample;
导入java.io.IOException;
导入org.apache.http.client.ClientProtocolException;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.message.BasicNameValuePair;
导入android.app.Activity;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
公共类HttpPostExample扩展活动{
按钮发送按钮;
编辑文本msgTextField;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//加载布局
setContentView(R.layout.activity\u http\u post\u示例);
//使消息文本字段成为对象
msgTextField=(EditText)findViewById(R.id.msgTextField);
//生成发送按钮对象
sendButton=(按钮)findViewById(R.id.sendButton);
}
//这是单击按钮时调用的函数
公共无效发送(视图五)
{
//从消息文本框中获取消息
字符串msg=msgTextField.getText().toString();
//确保字段不是空的
如果(msg.length()>0)
{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.eeecoderpages.orgfree.com/post.php");
试一试{
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“id”,“12345”);
添加(新的BasicNameValuePair(“消息”,msg));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(“”;//清除文本框
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
}
其他的
{
//如果文本字段为空,则显示消息
Toast.makeText(getBaseContext(),“所有字段都是必需的”,Toast.LENGTH_SHORT.show();
}
}
}
这是我的xml gui文件:

<?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>

我还将internet权限添加到清单中:

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

在Web服务器端,我使用了以下php脚本:

<?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;


    ?>


但它不起作用当我按下发送按钮时,系统关闭了我的应用。我搜索了很多解决方案,但没有一个适合我。任何人的帮助我都会感激的

听起来您好像遇到了
NetworkOnMainThread
异常

原因:您正在主UI线程上执行
网络操作


解决方案:使用
AsyncTask

听起来您好像遇到了
networkMainThread
异常

原因:您正在主UI线程上执行
网络操作


解决方案:使用
AsyncTask

您正在主ui线程上执行与网络相关的操作。使用
线程
异步任务

您将获得
networkonmainthreadeception
post蜂巢

      new PostTask().execute();
异步任务

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

使用
onPreExecute
onPostExecute
进行ui更新。

您正在主ui线程上执行与网络相关的操作。使用
线程
异步任务

您将获得
networkonmainthreadeception
post蜂巢

      new PostTask().execute();
异步任务

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

使用
onPreExecute
onPostExecute
进行ui更新。

不允许在ui主线程上进行网络操作

试试下面的代码

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
    }

}
注意

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

    }

}

doInBackground()
方法中不允许更新TextView、EditText或将图像设置为ImageView等UI操作。您可以在
onPostExecute()
onPreExecute()

中执行此操作,但不允许在UI主线程上执行网络操作

试试下面的代码

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
    }

}
注意

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

    }

}

doInBackground()
方法中不允许更新TextView、EditText或将图像设置为ImageView等UI操作。您可以在
onPostExecute()
onPreExecute()

日志猫说什么
NetworkOnMainThreadexception
?伙计们,谢谢你们的回答!。但它仍然不起作用。。发送按钮现在是好的。当我再按按钮时,应用程序不会崩溃。但是在我的php网站上没有我发送的任何数据。请帮忙。为什么它不起作用?我不明白。我还向html文件添加了读写权限。它仍然没有收到我从android发送的新数据。。另外,当我打开应用程序并按下按钮发送数据时,错误日志中没有任何错误。日志猫怎么说
NetworkOnMainThreadexception
?伙计们,谢谢你们的回答!。但它仍然不起作用。。发送按钮现在是好的。当我再按按钮时,应用程序不会崩溃。但是在我的php网站上没有我发送的任何数据。请帮忙。为什么它不起作用?我不明白。我还向html文件添加了读写权限。它仍然没有收到我从android发送的新数据。。此外,当我打开应用程序并按下按钮发送数据时,错误日志中没有任何错误。请阅读