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

url地址需要自己改一下

测试以后在修改,此版本为未改正版

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.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

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());
            }
        });
    }
    public void ReadNet(String url){
        new AsyncTask<String, Void, String>() {
            @Override
            protected String doInBackground(String... params) {
                String urlString =params[0];
                HttpGet get =new HttpGet(urlString);
                try {
                    HttpResponse response=client.execute(get);
                    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);
    }
}


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