博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
URLConnection和HttpClient使用入门
阅读量:4207 次
发布时间:2019-05-26

本文共 3753 字,大约阅读时间需要 12 分钟。

本讲内容:URLConnection和HttpClient使用入门

在Android中除了使用WebView控件访问网络以外,还有用代码方式访问网络的方法,代码方式有时候会显得更加灵活。本讲会介绍使用URLConnection对象和HttpClient组件访问网络的方法。而这两种方法和Java Web开发中的使用方式几乎没有区别,而Web开发的相关资料比比皆是,因此有兴趣的同学学完本讲之后可以专门去研究一下HttpClient4.0的内容,以求更深入的学习。
一、分别使用URLConnection和HttpClient访问Google天气服务的例子
这个例子的的目的就是从Google哪里获取郑州的天气预报信息,并显示在TextView中,本讲只会把返回的XML数据显示出来,下一讲我们学XML解析的时候再把这个天气预报做成图文并茂的形式,所以大家先暂时忍耐一下丑陋的界面。
1、新建一个项目 Lesson30_HttpClient ,主Activity的文件名是 MainActivity.java
2、res/layout/main.xml的内容如下:

3、MainActivity.java的内容如下:

package android.basic.lesson30;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import org.apache.http.client.ResponseHandler;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.BasicResponseHandler;import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {	TextView tv;	String googleWeatherUrl1 = "http://www.google.com/ig/api?weather=zhengzhou";	String googleWeatherUrl2 = "http://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";		/** Called when the activity is first created. */	@Override	public void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.main);		// 定义UI组件		Button b1 = (Button) findViewById(R.id.Button01);		Button b2 = (Button) findViewById(R.id.Button02);		tv = (TextView) findViewById(R.id.TextView02);		// 设置按钮单击监听器		b1.setOnClickListener(new View.OnClickListener() {			@Override			public void onClick(View v) {				// 使用URLConnection连接GoogleWeatherAPI				urlConn();			}		});		// 设置按钮单击监听器		b2.setOnClickListener(new View.OnClickListener() {			@Override			public void onClick(View v) {				// 使用HttpCient连接GoogleWeatherAPI				httpClientConn();			}		});	}	// 使用URLConnection连接GoogleWeatherAPI	protected void urlConn() {		try {			// URL			URL url = new URL(googleWeatherUrl1);			// HttpURLConnection			HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();			if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {				Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",						Toast.LENGTH_SHORT).show();				// InputStreamReader				InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");				int i;				String content = "";				// read				while ((i = isr.read()) != -1) {					content = content + (char) i;				}				isr.close();				//设置TextView				tv.setText(content);			}			//disconnect			httpconn.disconnect();		} catch (Exception e) {			Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)					.show();			e.printStackTrace();		}	}	// 使用HttpCient连接GoogleWeatherAPI	protected void httpClientConn() {		//DefaultHttpClient		DefaultHttpClient httpclient = new DefaultHttpClient();		//HttpGet		HttpGet httpget = new HttpGet(googleWeatherUrl2);		//ResponseHandler		ResponseHandler
responseHandler = new BasicResponseHandler(); try { String content = httpclient.execute(httpget, responseHandler); Toast.makeText(getApplicationContext(), "连接Google Weather API成功!", Toast.LENGTH_SHORT).show(); //设置TextView tv.setText(content); } catch (Exception e) { Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT) .show(); e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); }}
4、最后别忘了在AndroidManifest.xml中加入访问网络的权限,<uses-permission android:name="android.permission.INTERNET"></uses-permission>
5、运行程序查看结果:

image

按第一个按钮的效果,返回的数据结果显示在了TextView里。

image

按第二个按钮的效果,返回的数据结果显示在了TextView里, 所不同的是显示的是中文。

转载地址:http://zllli.baihongyu.com/

你可能感兴趣的文章
通过LR监控Linux服务器性能
查看>>
通过FTP服务的winsockes录制脚本
查看>>
LRwinsocket协议测试AAA服务器
查看>>
Net远程管理实验
查看>>
反病毒专家谈虚拟机技术 面临两大技术难题
查看>>
几种典型的反病毒技术:特征码技术、覆盖法技术等
查看>>
性能测试一般过程与LR性能测试过程
查看>>
Software Security Testing软件安全测试
查看>>
SQL注入漏洞全接触--进阶篇
查看>>
SQL注入漏洞全接触--高级篇
查看>>
SQL注入法攻击一日通
查看>>
论文浅尝 | 通过共享表示和结构化预测进行事件和事件时序关系的联合抽取
查看>>
论文浅尝 | 融合多粒度信息和外部语言知识的中文关系抽取
查看>>
论文浅尝 | GMNN: Graph Markov Neural Networks
查看>>
廖雪峰Python教程 学习笔记3 hello.py
查看>>
从内核看epoll的实现(基于5.9.9)
查看>>
python与正则表达式
查看>>
安装.Net Framework 4.7.2时出现“不受信任提供程序信任的根证书中终止”的解决方法
查看>>
input type=“button“与input type=“submit“的区别
查看>>
解决Github代码下载慢问题!
查看>>