[转帖]URLConnection和HttpClient使用入门_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2939 | 回复: 0   主题: [转帖]URLConnection和HttpClient使用入门        下一篇 
刘伟
注册用户
等级:少校
经验:938
发帖:82
精华:0
注册:2013-6-24
状态:离线
发送短消息息给刘伟 加好友    发送短消息息给刘伟 发消息
发表于: IP:您无权察看 2013-6-28 9:57:33 | [全部帖] [楼主帖] 楼主

本讲内容: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的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/TextView01" android:text="网络连接测试">
<button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button01" android:text="使用URLConnection访问GoogleWeatherAPI">
</button>
<button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button02" android:text="使用HttpClient访问GoogleWeatherAPI">
</button>
<scrollview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ScrollView01">
<textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView02">
</textview>
</scrollview>
</textview></linearlayout>


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<string> 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、运行程序查看结果:

北京联动北方科技有限公司

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

北京联动北方科技有限公司

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




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论