java - 安卓HTTP-POST

标签 java android httpclient

很好,英文不多,但尽量说清楚。

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

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

我正在使用 Android Studio。

我公开我拥有的数据。

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

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

}

最佳答案

您需要使用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);
        }

       }
}

关于java - 安卓HTTP-POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22733870/

相关文章:

android - Dex 无法在新的 Android 平台工具 (V8) 上处理路径中的空格

c# - 我应该将 Using 语句与 HttpClient 一起使用吗?

httpclient - 如何在 C# 中包装 HttpClient 以实现可测试性

java - 使用蓝牙键盘和语音助手的TextView按钮

java - 无法在 Java 中使用 DataOutputStream 写入整数

c# - 无法以与 C# 相同的格式为 WCF 服务传递 java 参数

android - ListView 仅显示最后一个元素

java - 使用 Apache HttpClient 的 Https 和基本身份验证

java - 如何调用另一个类的方法?

java - jdk/bin/java 和 jdk/jre/bin/java 的区别