|
既然Android定位为“网络操作系统”,自然提供了很威水的网络访问接口。既有java.net.*,又有org.apache.http.*,在数据处理方面支持json,xml等常用的数据格式。
Java代码: public class HttpDemo extends Activity {
private static final int MSGWHAT = 0x000000;
private TextView textView;
private Button btnLink;
private EditText etUrl;
private String data;
/**
* 消息控制器,用来更新界面,因为在普通线程是无法用来更新界面的
*/
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSGWHAT:
//设置显示文本
textView.setText(data);
break;
default:
break;
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//注意界面控件的初始化的位置,不要放在setContentView()前面
initComponent();
btnLink.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//可以放在另外的线程完成
try {
data = getData();
} catch (ClientProtocolException e) {
data = e.getMessage();
} catch (IOException e) {
data = e.getMessage();
} catch (URISyntaxException e) {
data = e.getMessage();
}
Message msg = new Message();
msg.what = MSGWHAT;
handler.sendMessage(msg);
}
});
}
/**
* 初始化界面组件
*/
private void initComponent() {
textView = (TextView) findViewById(R.id.text);
btnLink = (Button) findViewById(R.id.btn_link);
etUrl = (EditText) findViewById(R.id.url);
}
/**
* 取数据
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws URISyntaxException
*/
private String getData() throws ClientProtocolException, IOException, URISyntaxException {
String urlString = etUrl.getText().toString();
return request(urlString);
}
/**
* 发送请求
* @param url 请求地址
* @return
* @throws ClientProtocolException
* @throws IOException
* @throws URISyntaxException
*/
private String request(String url) throws ClientProtocolException, IOException, URISyntaxException {
HttpClient httpClient = new DefaultHttpClient();
URI uri = URIUtils.createURI("http", url, -1, null, null, null);
HttpGet get = new HttpGet(uri);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return httpClient.execute(get, responseHandler);
}
@Override
protected void onDestroy() {
super.onDestroy();
System.gc();
System.exit(0);
}
}
复制代码 |
|