码迷,mamicode.com
首页 > 移动开发 > 详细

【黑马Android】(06)使用HttpClient方式请求网络/网易新闻案例

时间:2016-04-24 23:17:03      阅读:588      评论:0      收藏:0      [点我收藏+]

标签:

使用HttpClient方式请求网络

技术分享

技术分享

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入姓名" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doGet"
        android:text="Get方式提交" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doPost"
        android:text="Post方式提交" />
</LinearLayout>
package com.itheim28.submitdata.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class NetUtils2 {

	private static final String TAG = "NetUtils";
	
	/**
	 * 使用post的方式登录
	 * @param userName
	 * @param password
	 * @return
	 */
	public static String loginOfPost(String userName, String password) {
		HttpClient client = null;
		try {
			// 定义一个客户端
			client = new DefaultHttpClient();
			
			// 定义post方法
			HttpPost post = new HttpPost("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet");
			
			// 定义post请求的参数
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("username", userName));
			parameters.add(new BasicNameValuePair("password", password));
			
			// 把post请求的参数包装了一层.
			
			// 不写编码名称服务器收数据时乱码. 需要指定字符集为utf-8
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
			// 设置参数.
			post.setEntity(entity);
			
			// 设置请求头消息
//			post.addHeader("Content-Length", "20");
			
			// 使用客户端执行post方法
			HttpResponse response = client.execute(post);	// 开始执行post请求, 会返回给我们一个HttpResponse对象
			
			// 使用响应对象, 获得状态码, 处理内容
			int statusCode = response.getStatusLine().getStatusCode();	// 获得状态码
			if(statusCode == 200) {
				// 使用响应对象获得实体, 获得输入流
				InputStream is = response.getEntity().getContent();
				String text = getStringFromInputStream(is);
				return text;
			} else {
				Log.i(TAG, "请求失败: " + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(client != null) {
				client.getConnectionManager().shutdown();	// 关闭连接和释放资源
			}
		}
		return null;
	}

	/**
	 * 使用get的方式登录
	 * @param userName
	 * @param password
	 * @return 登录的状态
	 */
	public static String loginOfGet(String userName, String password) {
		HttpClient client = null;
		try {
			// 定义一个客户端
			client = new DefaultHttpClient();
			
			// 定义一个get请求方法
			String data = "username=" + userName + "&password=" + password;
			HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data);
			
			// response 服务器相应对象, 其中包含了状态信息和服务器返回的数据
			HttpResponse response = client.execute(get);	// 开始执行get方法, 请求网络
			
			// 获得响应码
			int statusCode = response.getStatusLine().getStatusCode();
			
			if(statusCode == 200) {
				InputStream is = response.getEntity().getContent();
				String text = getStringFromInputStream(is);
				return text;
			} else {
				Log.i(TAG, "请求失败: " + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(client != null) {
				client.getConnectionManager().shutdown();	// 关闭连接, 和释放资源
			}
		}
		return null;
	}
	
	/**
	 * 根据流返回一个字符串信息
	 * @param is
	 * @return
	 * @throws IOException 
	 */
	private static String getStringFromInputStream(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		
		while((len = is.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		is.close();
		
		String html = baos.toString();	// 把流中的数据转换成字符串, 采用的编码是: utf-8
		
//		String html = new String(baos.toByteArray(), "GBK");
		
		baos.close();
		return html;
	}
}
package com.itheim28.submitdata;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.itheim28.submitdata.utils.NetUtils;
import com.itheim28.submitdata.utils.NetUtils2;

public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";
	private EditText etUserName;
	private EditText etPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		etUserName = (EditText) findViewById(R.id.et_username);
		etPassword = (EditText) findViewById(R.id.et_password);
	}
	
	/**
	 * 使用httpClient方式提交get请求
	 * @param v
	 */
	public void doHttpClientOfGet(View v) {
		Log.i(TAG, "doHttpClientOfGet");
		final String userName = etUserName.getText().toString();
		final String password = etPassword.getText().toString();
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 请求网络
				final String state = NetUtils2.loginOfGet(userName, password);
				// 执行任务在主线程中
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 就是在主线程中操作
						Toast.makeText(MainActivity.this, state, 0).show();
					}
				});
			}}).start();
	}
	

	/**
	 * 使用httpClient方式提交post请求
	 * @param v
	 */
	public void doHttpClientOfPost(View v) {
		Log.i(TAG, "doHttpClientOfPost");
		final String userName = etUserName.getText().toString();
		final String password = etPassword.getText().toString();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				final String state = NetUtils2.loginOfPost(userName, password);
				// 执行任务在主线程中
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 就是在主线程中操作
						Toast.makeText(MainActivity.this, state, 0).show();
					}
				});
			}
		}).start();
	}

	public void doGet(View v) {
		final String userName = etUserName.getText().toString();
		final String password = etPassword.getText().toString();
		
		new Thread(
				new Runnable() {
					
					@Override
					public void run() {
						// 使用get方式抓去数据
						final String state = NetUtils.loginOfGet(userName, password);
						
						// 执行任务在主线程中
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// 就是在主线程中操作
								Toast.makeText(MainActivity.this, state, 0).show();
							}
						});
					}
				}).start();
	}
	
	public void doPost(View v) {
		final String userName = etUserName.getText().toString();
		final String password = etPassword.getText().toString();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				final String state = NetUtils.loginOfPost(userName, password);
				// 执行任务在主线程中
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// 就是在主线程中操作
						Toast.makeText(MainActivity.this, state, 0).show();
					}
				});
			}
		}).start();
	}
}

网易新闻案例-1

Java-web: servlet服务端;

<?xml version="1.0" encoding="UTF-8" ?>
<news>
	<new>
		<title>3Q大战宣判: 腾讯获赔500万</title>
		<detail>最高法驳回360上诉, 维持一审宣判.</detail>
		<comment>6427</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/1.jpg</image>
	</new>
	<new>
		<title>今日之声:北大雕塑被戴口罩</title>
		<detail>市民: 因雾霾起诉环保局; 公务员谈"紧日子": 坚决不出去.</detail>
		<comment>681</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/2.jpg</image>
	</new>
	<new>
		<title>奥巴马见达赖是装蒜</title>
		<detail>外文局: 国际民众认可中国大国地位;法院: "流量清零"未侵权.</detail>
		<comment>1359</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/3.jpg</image>
	</new>
	<new>
		<title>轻松一刻: 我要沉迷学习不自拔</title>
		<detail>放假时我醒了不代表我起床了, 如今我起床了不代表我醒了!</detail>
		<comment>10116</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/4.jpg</image>
	</new>
	<new>
		<title>男女那些事儿</title>
		<detail>"妈, 我在东莞被抓, 要2万保释金, 快汇钱到xxx!"</detail>
		<comment>10339</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/5.jpg</image>
	</new>
	<new>
		<title>3Q大战宣判: 腾讯获赔500万</title>
		<detail>最高法驳回360上诉, 维持一审宣判.</detail>
		<comment>6427</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/1.jpg</image>
	</new>
	<new>
		<title>今日之声:北大雕塑被戴口罩</title>
		<detail>市民: 因雾霾起诉环保局; 公务员谈"紧日子": 坚决不出去.</detail>
		<comment>681</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/2.jpg</image>
	</new>
	<new>
		<title>奥巴马见达赖是装蒜</title>
		<detail>外文局: 国际民众认可中国大国地位;法院: "流量清零"未侵权.</detail>
		<comment>1359</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/3.jpg</image>
	</new>
	<new>
		<title>轻松一刻: 我要沉迷学习不自拔</title>
		<detail>放假时我醒了不代表我起床了, 如今我起床了不代表我醒了!</detail>
		<comment>10116</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/4.jpg</image>
	</new>
	<new>
		<title>男女那些事儿</title>
		<detail>"妈, 我在东莞被抓, 要2万保释金, 快汇钱到xxx!"</detail>
		<comment>10339</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/5.jpg</image>
	</new>
	<new>
		<title>3Q大战宣判: 腾讯获赔500万</title>
		<detail>最高法驳回360上诉, 维持一审宣判.</detail>
		<comment>6427</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/1.jpg</image>
	</new>
	<new>
		<title>今日之声:北大雕塑被戴口罩</title>
		<detail>市民: 因雾霾起诉环保局; 公务员谈"紧日子": 坚决不出去.</detail>
		<comment>681</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/2.jpg</image>
	</new>
	<new>
		<title>奥巴马见达赖是装蒜</title>
		<detail>外文局: 国际民众认可中国大国地位;法院: "流量清零"未侵权.</detail>
		<comment>1359</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/3.jpg</image>
	</new>
	<new>
		<title>轻松一刻: 我要沉迷学习不自拔</title>
		<detail>放假时我醒了不代表我起床了, 如今我起床了不代表我醒了!</detail>
		<comment>10116</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/4.jpg</image>
	</new>
	<new>
		<title>男女那些事儿</title>
		<detail>"妈, 我在东莞被抓, 要2万保释金, 快汇钱到xxx!"</detail>
		<comment>10339</comment>
		<image>http://10.0.2.2:8080/NetEaseServer/images/5.jpg</image>
	</new>
</news>
技术分享

网易新闻案例-2

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima28.neteasedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima28.neteasedemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lv_news"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

listview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dip" >

    <com.loopj.android.image.SmartImageView
        android:id="@+id/siv_listview_item_icon"
        android:layout_width="100dip"
        android:layout_height="60dip"
        android:src="@drawable/a" />

    <TextView
        android:id="@+id/tv_listview_item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dip"
        android:layout_toRightOf="@id/siv_listview_item_icon"
        android:singleLine="true"
        android:text="3Q大战宣判: 腾讯获赔500万"
        android:textColor="@android:color/black"
        android:textSize="17sp" />

    <TextView
        android:id="@+id/tv_listview_item_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/tv_listview_item_title"
        android:layout_below="@id/tv_listview_item_title"
        android:layout_marginTop="3dip"
        android:text="啊发送旅客登机挥发速度发送旅客登机"
        android:textColor="@android:color/darker_gray"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tv_listview_item_comment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="668跟帖"
        android:textColor="#FF0000"
        android:textSize="12sp" />

</RelativeLayout>
package com.itheima28.neteasedemo.domain;

/**
 * @author andong
 * 新闻信息实体类
 */
public class NewInfo {

	private String title; // 标题
	private String detail; // 详细
	private Integer comment; // 跟帖数量
	private String imageUrl; // 图片连接
	@Override
	public String toString() {
		return "NewInfo [title=" + title + ", detail=" + detail + ", comment="
				+ comment + ", imageUrl=" + imageUrl + "]";
	}
	public NewInfo(String title, String detail, Integer comment, String imageUrl) {
		super();
		this.title = title;
		this.detail = detail;
		this.comment = comment;
		this.imageUrl = imageUrl;
	}
	public NewInfo() {
		super();
		// TODO Auto-generated constructor stub
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDetail() {
		return detail;
	}
	public void setDetail(String detail) {
		this.detail = detail;
	}
	public Integer getComment() {
		return comment;
	}
	public void setComment(Integer comment) {
		this.comment = comment;
	}
	public String getImageUrl() {
		return imageUrl;
	}
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}
}
package com.itheima28.neteasedemo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;

import com.itheima28.neteasedemo.domain.NewInfo;
import com.loopj.android.image.SmartImageView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private final int SUCCESS = 0;
    private final int FAILED = 1;
	private ListView lvNews;
	private List<NewInfo> newInfoList;
    
    private Handler handler = new Handler() {

		/**
    	 * 接收消息
    	 */
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:		// 访问成功, 有数据
				// 给Listview列表绑定数据
				
				newInfoList = (List<NewInfo>) msg.obj;

				MyAdapter adapter = new MyAdapter();
				lvNews.setAdapter(adapter);
				break;
			case FAILED:	// 无数据
				Toast.makeText(MainActivity.this, "当前网络崩溃了.", 0).show();
				break;
			default:
				break;
			}
		}
    };

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        init();
    }

	private void init() {
		lvNews = (ListView) findViewById(R.id.lv_news);

		// 抓取新闻数据
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 获得新闻集合
				List<NewInfo> newInfoList = getNewsFromInternet();
				Message msg = new Message();
				if(newInfoList != null) {
					msg.what = SUCCESS;
					msg.obj = newInfoList;
				} else {
					msg.what = FAILED;
				}
				handler.sendMessage(msg);
			}
		}).start();
		
		
	}

	/**
	 * 返回新闻信息
	 */
	private List<NewInfo> getNewsFromInternet() {
		HttpClient client = null;
		try {
			// 定义一个客户端
			client = new DefaultHttpClient();
			
			// 定义get方法
			HttpGet get = new HttpGet("http://192.168.1.254:8080/NetEaseServer/new.xml");
			
			// 执行请求
			HttpResponse response = client.execute(get);
			
			int statusCode = response.getStatusLine().getStatusCode();
			
			if(statusCode == 200) {
				InputStream is = response.getEntity().getContent();
				List<NewInfo> newInfoList = getNewListFromInputStream(is);
				return newInfoList;
			} else {
				Log.i(TAG, "访问失败: " + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(client != null) {
				client.getConnectionManager().shutdown();		// 关闭和释放资源
			}
		}
		return null;
	}
    
	/**
	 * 从流中解析新闻集合
	 * @param is
	 * @return
	 */
	private List<NewInfo> getNewListFromInputStream(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();	// 创建一个pull解析器
		parser.setInput(is, "utf-8");	// 指定解析流, 和编码
		
		int eventType = parser.getEventType();
		
		List<NewInfo> newInfoList = null;
		NewInfo newInfo = null;
		while(eventType != XmlPullParser.END_DOCUMENT) {	// 如果没有到结尾处, 继续循环
			
			String tagName = parser.getName();	// 节点名称
			switch (eventType) {
			case XmlPullParser.START_TAG: // <news>
				if("news".equals(tagName)) {
					newInfoList = new ArrayList<NewInfo>();
				} else if("new".equals(tagName)) {
					newInfo = new NewInfo();
				} else if("title".equals(tagName)) {
					newInfo.setTitle(parser.nextText());
				} else if("detail".equals(tagName)) {
					newInfo.setDetail(parser.nextText());
				} else if("comment".equals(tagName)) {
					newInfo.setComment(Integer.valueOf(parser.nextText()));
				} else if("image".equals(tagName)) {
					newInfo.setImageUrl(parser.nextText());
				}
				break;
			case XmlPullParser.END_TAG:	// </news>
				if("new".equals(tagName)) {
					newInfoList.add(newInfo);
				}
				break;
			default:
				break;
			}
			eventType = parser.next();		// 取下一个事件类型
		}
		return newInfoList;
	}
	
	class MyAdapter extends BaseAdapter {

		/**
		 * 返回列表的总长度
		 */
		@Override
		public int getCount() {
			return newInfoList.size();
		}

		/**
		 * 返回一个列表的子条目的布局
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			
			if(convertView == null) {
				LayoutInflater inflater = getLayoutInflater();
				view = inflater.inflate(R.layout.listview_item, null);
			} else {
				view = convertView;
			}
			
			// 重新赋值, 不会产生缓存对象中原有数据保留的现象
			SmartImageView sivIcon = (SmartImageView) view.findViewById(R.id.siv_listview_item_icon);
			TextView tvTitle = (TextView) view.findViewById(R.id.tv_listview_item_title);
			TextView tvDetail = (TextView) view.findViewById(R.id.tv_listview_item_detail);
			TextView tvComment = (TextView) view.findViewById(R.id.tv_listview_item_comment);
			
			NewInfo newInfo = newInfoList.get(position);
			
			sivIcon.setImageUrl(newInfo.getImageUrl());		// 设置图片
			tvTitle.setText(newInfo.getTitle());
			tvDetail.setText(newInfo.getDetail());
			tvComment.setText(newInfo.getComment() + "跟帖");
			return view;
		}
		

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
	}
}


【黑马Android】(06)使用HttpClient方式请求网络/网易新闻案例

标签:

原文地址:http://blog.csdn.net/waldmer/article/details/51217097

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!