快捷搜索:

Android开发——HTTP通讯

说Android是一款互联网手机操作系统一点也不过为过。打开G2的"大年夜抽屉”,一大年夜堆的软件,大年夜部分都是必要收集支持才能正常运行的。

曾经和同砚说:没有收集支持,G2跟Nokia 1200没啥差别!

既然Android定位为“收集操作系统”,自然供给了很威水的收集造访接口。既有java.net.*,又有org.apache.http.*,在数据处置惩罚方面支持json,xml等常用的数据款式。

示例代码如下:

1:

2: public class HttpDemo extends Activity {

3:

4:private static final int MSGWHAT = 0x000000;

5:

6:private TextView textView;

7:private Button btnLink;

8:private EditText etUrl;

9:private String data;

10:/**

11:* 消息节制器,用来更新界面,由于在通俗线程是无法用来更新界面的

12:*/

13:private Handler handler = new Handler() {

14:@Override

15:public void handleMessage(Message msg) {

16:switch (msg.what) {

17:case MSGWHAT:

18://设置显示文本

19:textView.setText(data);

20:break;

21:default:

22:break;

23:}

24:}

25:};

26:

27:/** Called when the activity is first created. */

28:@Override

29:public void onCreate(Bundle savedInstanceState) {

30:super.onCreate(savedInstanceState);

31:setContentView(R.layout.main);

32://留意界面控件的初始化的位置,不要放在setContentView()前面

33:initComponent();

34:btnLink.setOnClickListener(new OnClickListener() {

35:

36:@Override

37:public void onClick(View v) {

38://可以放在别的的线程完成

39:try {

40:data = getData();

41:} catch (ClientProtocolException e) {

42:data = e.getMessage();

43:} catch (IOException e) {

44:data = e.getMessage();

45:} catch (URISyntaxException e) {

46:data = e.getMessage();

47:}

48:Message msg = new Message();

49:msg.what = MSGWHAT;

50:handler.sendMessage(msg);

51:}

52:});

53:}

54:

55:/**

56:* 初始化界面组件

57:*/

58:private void initComponent() {

59:textView = (TextView) findViewById(R.id.text);

60:btnLink = (Button) findViewById(R.id.btn_link);

61:etUrl = (EditText) findViewById(R.id.url);

62:}

63:

64:/**

65:* 取数据

66:* @return

67:* @throws ClientProtocolException

68:* @throws IOException

69:* @throws URISyntaxException

70:*/

71:private String getData() throws ClientProtocolException, IOException, URISyntaxException {

72:String urlString = etUrl.getText().toString();

73:return request(urlString);

74:}

75:

76:/**

77:* 发送哀求

78:* @param url 哀求地址

79:* @return

80:* @throws ClientProtocolException

81:* @throws IOException

82:* @throws URISyntaxException

83:*/

84:private String request(String url) throws ClientProtocolException, IOException, URISyntaxException {

85:HttpClient httpClient = new DefaultHttpClient();

86:URI uri = URIUtils.createURI("http", url, -1, null, null, null);

87:HttpGet get = new HttpGet(uri);

88:ResponseHandler responseHandler = new BasicResponseHandler();

89:return httpClient.execute(get, responseHandler);

90:}

91:

92:@Override

93:protected void onDestroy() {

94:super.onDestroy();

95:System.gc();

96:System.exit(0);

97:}

98: }

您可能还会对下面的文章感兴趣: