Android HTTP-POST

时间:2014-03-29 16:48:23

标签: java android httpclient

好,英语不多,但要尽可能清楚。

我是java的新手。我几天前就开始了。我正在尝试开发一个网站阅读arhico php。但它不起作用。总是给我回报

我认为我们应该对Thread做些什么,但我不知道怎么做。

我正在使用Android工作室。

我公开了我拥有的数据。

的AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:maxSdkVersion="15"/>
    <uses-permission android:name="android.permission.INTERNETr"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.tuto1.app.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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.tuto1.app.MainActivity">

<TextView
    android:text="@string/hello_world"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:background="#044234"
    android:textColor="#ffff"
    android:textSize="30sp"
    android:id="@+id/text1" />

MainActivity.java

package com.example.tuto1.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        httpHandler handler = new httpHandler();
        String txt = handler.post("http://demo.com/demo.php");

        TextView t = (TextView)findViewById(R.id.text1);
        t.setText(txt);



    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

httpHander.java(Class)

package com.example.tuto1.app;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;

public class httpHandler {

    public String post(String posturl){

        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(posturl);

            HttpResponse resp = httpclient.execute(httppost);
            HttpEntity ent = resp.getEntity();

            String text = EntityUtils.toString(ent);

            return text;

        }
        catch (Exception e) { return "mi error"; }

    }

}

已更新解决方案就是这样。

    import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        class TheTask extends AsyncTask<String,Void,String>
        {

            @Override
            protected String doInBackground(String... arg0) {
                String text =null;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(arg0[0]);
                    HttpResponse resp = httpclient.execute(httppost);
                    HttpEntity ent = resp.getEntity();
                    text = EntityUtils.toString(ent);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                return text;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                TextView t = (TextView)findViewById(R.id.text1);
                t.setText(result);
            }

        }

        new TheTask().execute("http://demo.com/php.php");


    }


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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

1 个答案:

答案 0 :(得分:1)

您需要使用ThreadAysnctaskVolley库。您无法在主UI线程上运行网络操作。

HttpResponse resp = httpclient.execute(httppost); // must be in a thread.

你可以创建自己的java线程,但asynctask使它更容易。您将找到信息和示例@

http://developer.android.com/reference/android/os/AsyncTask.html

示例:

public class MainActivity extends Activity {
       TextView t;  
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main); // activity main is the activity that you are currently working with
            t = (TextView)findViewById(R.id.text1); // this is the text view where you want the text response to appear.
            new TheTask().execute("http://demo.com/demo.php");
        }

       class TheTask extends AsyncTask<String,Void,String>
       {

        @Override
        protected String doInBackground(String... arg0) {
            String text =null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(arg0[0]);
                HttpResponse resp = httpclient.execute(httppost);
                HttpEntity ent = resp.getEntity();
                text = EntityUtils.toString(ent);
            }
            catch (Exception e) 
            { 
                 e.printStackTrace();
            }

            return text;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            t.setText(result);
        }

       }
}