之前在自己公司做的手機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的