0

您好,我想使用 Httppost 将字符串从我的 android 应用程序发布到 PHP 中的网站。应用程序布局由一个文本框和一个发送按钮组成。当我单击发送按钮时,应用程序崩溃并显示一条消息不幸的是应用程序停止工作。任何机构都可以提供如何解决这个问题。

MainActivity.java 文件

 package com.example.test5;

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import com.example.test5.R;

    import android.os.Bundle;
    import android.app.Activity;
    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 {

         Button sendButton;

            EditText msgTextField;

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

                // 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://thawide.com/androidtest.php");

                   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                   nameValuePairs.add(new BasicNameValuePair("id", "12345"));
                   nameValuePairs.add(new BasicNameValuePair("message", msg));
                   try {
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                   try {
                    httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                  msgTextField.setText(""); // clear text box
                Toast.makeText(getBaseContext(),"sucess",Toast.LENGTH_SHORT).show();


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

            }


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

    }

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test5"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET">
    </uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.test5.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >



    <EditText
        android:id="@+id/msgTextField"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/sendButton"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="59dp"
        android:ems="10" />

    <Button
        android:id="@+id/sendButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/msgTextField"
        android:layout_marginTop="72dp"
        android:onClick="send"
        android:text="Send" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/msgTextField"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="60dp"
        android:text="Message" />


</RelativeLayout>

服务器端代码

<?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);
 $fh = fopen("androidmessages.html", "wb");
fwrite($fh, $message."<br />");
fclose($fh);
// 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;

?>
4

2 回答 2

0

您不应该在 UI 线程上执行网络 IO。您需要在后台线程上使用AsyncTaskThread执行网络事务。

您可以参考本教程以获得更多理解。

于 2013-08-07T19:18:55.260 回答
0

用 try catch 块包围 HttpClient 并将 Stack Trace 放在这里.. 您可以在 AsyncTask 中执行所有 Internet 请求,这非常易于使用并且不在 UI 线程中处理。

于 2013-08-07T23:51:13.463 回答