Android程序开发之网络通信(四): 使用HttpClient进行Post方式通信

未验证

MainActivity.java

package com.example.treasure.httpclient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

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

public class MainActivity extends Activity {
    private EditText getedit;
    private TextView gettext;
    HttpClient client;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        client=new DefaultHttpClient();
        getedit=(EditText)findViewById(R.id.getedit);
        gettext=(TextView)findViewById(R.id.gettext);
        findViewById(R.id.getbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReadNet("http://10.0.2.2:8080",getedit.getText().toString());
            }
        });
    }
    public void ReadNet(String url, String in){
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                String urlString =params[0];
               // HttpGet get =new HttpGet(urlString);
                HttpPost post=new HttpPost(urlString);
               // StringEntity entity= null;
                try {
                   // entity = new StringEntity(params[1]);
                    List<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>();
                    list.add(new BasicNameValuePair("name",params[1]));
                    post.setEntity(new UrlEncodedFormEntity(list));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                try {
                    HttpResponse response=client.execute(post);
                    String valus=EntityUtils.toString(response.getEntity());
                  //  System.out.println(valus);
                    return valus;
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                gettext.setText(s);
            }
        }.execute(url,in);
    }
}


你可能感兴趣的:(Android程序开发之网络通信(四): 使用HttpClient进行Post方式通信)