httpclient get post

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "visizen.com.httpclient"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile "org.apache.httpcomponents:httpcore:4.3.2"
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="visizen.com.httpclient" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
package visizen.com.httpclient;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

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

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

public class MainActivity extends AppCompatActivity {

    private static final int BADNET = 0;//网络异常
    private static final int BADSERVER = 1;//服务器异常
    private static final int RESPONSE_RESOULT = 2;//获取响应数据
    private Button getBtn;
    private Button postBtn;
    private TextView content;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BADNET:
                    Toast.makeText(MainActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    break;
                case BADSERVER:
                    Toast.makeText(MainActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                    break;
                case RESPONSE_RESOULT:
                    MainActivity.this.content.setText(msg.obj.toString());
                    break;
            }
        }
    };

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

        this.getBtn = (Button) findViewById(R.id.getBtn);
        this.postBtn = (Button) findViewById(R.id.postBtn);
        this.content = (TextView) findViewById(R.id.content);

    }

    public void getHandler(View view) {
        this.content.setText("get");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("http://www.baidu.com");
                try {
                    HttpResponse response = httpClient.execute(httpGet);
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        InputStream content = response.getEntity().getContent();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = content.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        String result = baos.toString();
                        content.close();
                        baos.close();

                        Message msg = new Message();
                        msg.what = RESPONSE_RESOULT;
                        msg.obj = result;
                        handler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = BADSERVER;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = BADNET;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    public void postHandler(View view) {
        this.content.setText("post");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://www.baidu.com");

                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                parameters.add(new BasicNameValuePair("name", "小明"));
                parameters.add(new BasicNameValuePair("password ", "123456"));

                HttpEntity entity = null;
                try {
                    entity = new UrlEncodedFormEntity(parameters, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                post.setEntity(entity);
                try {
                    HttpResponse response = client.execute(post);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        InputStream content = response.getEntity().getContent();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = content.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        String s = baos.toString();
                        baos.close();
                        content.close();
                    } else {

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
}

 

posted on 2015-12-02 15:53  jayhtt  阅读(94)  评论(0)    收藏  举报