Onelong

分享知识,与你一起进步......
RSS icon Home icon
  • android http-get方法简单实现

    post by onelong / 2010-9-10 1:10 Friday [android]

    package com.hl;

    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;

    import org.apache.http.util.ByteArrayBuffer;
    import org.apache.http.util.EncodingUtils;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    public class SimpleHTTPGet extends Activity {
      
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            TextView show = (TextView)findViewById(R.id.show);
           
            try {
       URL url = new URL("http://ways2u.com");
       URLConnection urlConnection = url.openConnection();
       InputStream is = urlConnection.getInputStream();
       
       /* 用ByteArrayBuffer做缓存 */
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
               
                while((current = is.read()) != -1){
                     baf.append((byte)current);
                }
               
                /* 将缓存的内容转化为String, 用UTF-8编码 */
                String myString = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
               //myString = new String(baf.toByteArray());
                show.setText(myString);
               
      } catch (Exception e) {
       e.printStackTrace();
      }
        }
    }

    引用地址:
     

    评论:

    1. Patricia
      Hey, subtle must be your midlde name. Great post!

    我要评论