HttpURLConnection访问百度

布局文件:




    

    

主类:

public class MainActivity extends Activity {
    protected static final int SUCCESS = 1;
    protected static final int ERROR = 2;

    private EditText et_path;
    private TextView tv_result;

    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    String text = (String) msg.obj;
                    tv_result.setText(text);
                    break;
                case ERROR:
                    Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_path = (EditText) findViewById(R.id.et_path);
        tv_result = (TextView) findViewById(R.id.tv_result);
    }
    /**
     * 查看源文件的点击事件
     * @param view
     */
    public void click(View view){
        final String path = et_path.getText().toString().trim();
        //访问网络,把html源文件下载下来
        new Thread(){
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");//声明请求方式 默认get
                    //conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android 2.3.3; zh-cn; sdk Build/GRI34) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/6.0.0.57_r870003.501 NetType/internet");
                    int code = conn.getResponseCode();
                    if(code ==200){
                        InputStream is = conn.getInputStream();
                        String result = StreamTools.readStream(is);

                        Message msg = Message.obtain();//减少消息创建的数量
                        msg.obj = result;
                        msg.what = SUCCESS;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    Message msg = Message.obtain();//减少消息创建的数量
                    msg.what = ERROR;
                    handler.sendMessage(msg);
                    e.printStackTrace();
                }
            };
        }.start();
    }
}


流的工具类:


/**
 * 流的工具类
 * @author Administrator
 *
 */
public class StreamTools {
    /**
     * 把输入流的内容转换成字符串
     * @param is
     * @return null解析失败, string读取成功
     */
    public static String readStream(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while( (len = is.read(buffer))!=-1){
                baos.write(buffer, 0, len);
            }
            is.close();
            String temptext = new String(baos.toByteArray());
            if(temptext.contains("charset=gb2312")){//解析meta标签
                return new String(baos.toByteArray(),"gb2312");
            }else{
                return new String(baos.toByteArray(),"utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}


你可能感兴趣的:(移动开发)