如何使用httpPost,应用程序崩溃将数据发送到一个网站 [英] How to send data to a website using httpPost, app crashes

查看:124
本文介绍了如何使用httpPost,应用程序崩溃将数据发送到一个网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我工作的一个项目。我需要从我的Andr​​oid应用程序发送一些数据到网络服务器。但是,当我碰到了发送按钮的应用程序崩溃。

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.

这是我的.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();
        }

    }

}

下面是我的XML GUI文件:

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>

而在网络服务器端,我用下面的 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;


    ?>

不过,这是行不通的。 当我碰到了发送按钮,系统关机我的应用程序。我搜索了很多解决方案,但非,他们对我的作品的。从任何机构的任何帮助,我将不胜感激!

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!

推荐答案

在UI主线程联网操作是不允许的。

Networking operation on UI Main thread are not allowed.

试试下面的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
    }

}

要使用code,

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

注意

UI如更新的TextView,EditText上或设置图像的ImageView操作未在 doInBackground()法允许的。你可以在 onPostExecute()在preExecute()

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

这篇关于如何使用httpPost,应用程序崩溃将数据发送到一个网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆