package com.example.eg18_2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    private TextView textView;
    private Button get,post;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
        .penaltyLog() //打印logcat，当然也可以定位到dropbox，通过文件保存相应的log
        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects() //探测SQLite数据库操作
        .penaltyLog() //打印logcat
        .penaltyDeath()
        .build()); 

        textView = (TextView)findViewById(R.id.textView);
        get = (Button)findViewById(R.id.get);
        post = (Button)findViewById(R.id.post);

        //绑定按钮监听器
        get.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //注意：此处ip不能用127.0.0.1或localhost
            	//Android模拟器已将它自己作为了localhost
                String uri = "http://192.168.0.5:8080/myapp/http.jsp?parameter=以Get方式发送请求";
                textView.setText(get(uri));
            }
        });
        //绑定按钮监听器
        post.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String uri = "http://192.168.0.5:8080/myapp/http.jsp";
                textView.setText(post(uri));
            }
        });
    }
    
    /**
     * 以get方式发送请求，访问web
     * @param uri web地址
     * @return 响应数据
     */
    private static String get(String uri){
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        try {
            //发送请求，得到响应
            HttpResponse response = client.execute(request);

            //请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                reader = new BufferedReader(
                		new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                String NL = System.getProperty("line.separator");
                while((line = reader.readLine()) != null){
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                if (null != reader){
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb){
            result =  sb.toString();
        }
        return result;
    }
    
    /**
     * 以post方式发送请求，访问web
     * @param uri web地址
     * @return 响应数据
     */
    private static String post(String uri){
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(uri);

        //保存要传递的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加参数
        params.add(new BasicNameValuePair("parameter","以Post方式发送请求"));

        try {
            //设置字符集
            HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");
            //请求对象
            request.setEntity(entity);
            //发送请求
            HttpResponse response = client.execute(request);

            //请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                System.out.println("post success");
                reader = new BufferedReader(
                		new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                String NL = System.getProperty("line.separator");
                while((line = reader.readLine()) != null){
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                //关闭流
                if (null != reader){
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb){
            result =  sb.toString();
        }
        return result;
    }
}
