Android HTTP協議(一)

來源:互聯網
上載者:User

之前在自己公司做的手機OS上開發,最痛苦的就是我們的系統沒有現成的HTTP協議,只有使用開源庫的libCurl進行封裝,在此過程中很好的熟悉了HTTP請求的一些細節,現在想想還是不錯的一個經曆,現在轉到Android上了,對於Google來說,如果連網都處理不好的話,號稱最好的互連網公司就太遜了吧。

 使用URLConnection樣本

下載html檔案,放到文本控制項中顯示

public class AndroidNetActivity extends Activity {
    
    Handler handler;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final EditText eText = (EditText)findViewById(R.id.address);
        final TextView tView = (TextView)findViewById(R.id.pagetext);
        
        handler = new Handler(){
            public void handleMessage(Message msg){
                switch(msg.what)
                {
                    case 0:
                    {
                        tView.append((String)msg.obj);
//                        tView.setText((String)msg.obj);
                        break;
                    }
                }
                super.handleMessage(msg);
                
            }
            
        };
        
        final Button button = (Button)findViewById(R.id.ButtonGo);
        button.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try{
                    tView.setText("");
                    URL url = new URL(eText.getText().toString());
                    URLConnection conn = url.openConnection();  
//                    //方式1
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));        
                    
                    String line = "";
                    while((line = rd.readLine())!= null)
                    {
                        Message lmsg;
                        lmsg = new Message();
                        lmsg.what = 0;                        
                        lmsg.obj = line;
                        AndroidNetActivity.this.handler.sendMessage(lmsg);
                    }
                    //方式2
//                    InputStream is = null;
//                    is = conn.getInputStream();
//                    byte[] result=null;
//                    
//                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                    while(true)
//                    {
//                        byte[] bytes = new byte[64];
//                        int tmp = is.read(bytes);
//                        if(tmp == -1)
//                        {
//                            break;
//                        }
//                        else
//                        {
//                            bos.write(bytes,0,tmp);
//                        }
//                    }
//                    result = bos.toByteArray();                    
//                    String all;
//                    all = new String(result);
//                    
//                    Message msg;
//                    msg = new Message();
//                    msg.what = 0;                        
//                    msg.obj = all;
//                    AndroidNetActivity.this.handler.sendMessage(msg);
               }
                catch(Exception e)
                {
                    e.printStackTrace();
                    }
                
            }
            
        });
    }
}

 

 HttpURLConnection

 繼承自URLConnection ,相當於封裝的HTTP協議吧。範例程式碼

 

    HttpURLConnection  conn=null;
    URL url;
    conn=(HttpURLConnection)url.openConnection();
    conn.setDoInput(true);   
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");  
    conn.setRequestProperty("Accept", "application/octet-stream, */*");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type","application/octet-stream");
    conn.connect();
    int code=conn.getResponseCode();
    int len=conn.getContentLength();

    if(conn==null)
    {
        return null;
    }
    InputStream is=null;
    byte[] result=null;
    ByteArrayOutputStream bos=new ByteArrayOutputStream();
    is=conn.getInputStream();
    while(true){
        byte[] bytes = new byte[64];
        int tmp=is.read(bytes);
        if(tmp==-1)
        {
            break;
        }
        else
        {
            bos.write(bytes, 0, tmp);
        }
        }
    result = bos.toByteArray();

 

下次整理一下HTTPClient的

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.