HttpURLConnection网络请求案例3



1.MaActivity.class

<span style="font-size:18px;">import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.updateversion.bean.InfoList;
import com.example.updateversion.bean.ZongBean;
import com.example.updateversion.utils.Utils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MainActivity extends Activity {
	private final String URL = "http://api.fang.anjuke.com/m/android/1.3/shouye/recInfosV3/?city_id=14&lat=40.04652&lng=116.306033&api_key=androidkey&sig=9317e9634b5fbc16078ab07abb6661c5&macid=45cd2478331b184ff0e15f29aaa89e3e&app=a-ajk&_pid=11738&o=PE-TL10-user+4.4.2+HuaweiPE-TL10+CHNC00B260+ota-rel-keys%2Crelease-keys&from=mobile&m=Android-PE-TL10&cv=9.5.1&cid=14&i=864601026706713&v=4.4.2&qtime=20160411091603&pm=b61&uuid=1848c59c-185d-48d9-b0e9-782016041109&_chat_id=";
	private PullToRefreshListView lv;
	private int x = 1;
	private boolean flag=true;
	private BaseAdapter base;
	Handler mHandler = new Handler() {
		@SuppressWarnings({ "rawtypes", "unchecked" })
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				// 解析的数据
				String str = (String) msg.obj;
				Gson gson = new Gson();
				ZongBean zongBean = gson.fromJson(str, ZongBean.class);
				final ImageLoader imageLoder = Utils.getImage(MainActivity.this);
				final ArrayList<InfoList> list = zongBean.getResult().getRows();
				Toast.makeText(MainActivity.this, list.size()+"", Toast.LENGTH_SHORT).show();
				if(flag){
					base=new BaseAdapter() {
					@Override
					public View getView(int position, View convertView, ViewGroup parent) {
						convertView = View.inflate(MainActivity.this, R.layout.lv_item, null);
						ImageView imaPic = (ImageView) convertView.findViewById(R.id.ima_item);
						TextView tvMsg = (TextView) convertView.findViewById(R.id.tv_msg);
						TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
						TextView tvAddre = (TextView) convertView.findViewById(R.id.tv_addre);
						imageLoder.displayImage(list.get(position).getInfo().getDefault_image(), imaPic);
						tvMsg.setText(list.get(position).getInfo().getRegion_title());
						tvAddre.setText(list.get(position).getInfo().getPrice());
						tvName.setText(list.get(position).getInfo().getLoupan_name());
						return convertView;
					}

					@Override
					public long getItemId(int position) {
						return position;
					}

					@Override
					public Object getItem(int position) {
						return list.get(position);
					}

					@Override
					public int getCount() {
						return list.size();
					}
				};
				lv.setAdapter(base);
				//flag=false;
				}
				lv.setOnRefreshListener(new OnRefreshListener2() {  
					@Override  
		            public void onPullDownToRefresh(PullToRefreshBase refreshView) {  
						x = x + 1;
						new Thread() {
							public void run() {
								try {
									getData(x);
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											lv.onRefreshComplete();
											base.notifyDataSetChanged();
										}
									});

								} catch (IOException e) {
									e.printStackTrace();
								}

							}

						}.start();

		            }  
					@Override  
		            public void onPullUpToRefresh(PullToRefreshBase refreshView) {  
						if(x>1){
						x = x - 1;
						new Thread() {
							public void run() {
								try {
									getData(x);
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											lv.onRefreshComplete();
											base.notifyDataSetChanged();
										}
									});

								} catch (IOException e) {
									e.printStackTrace();
								}

							}

						}.start();

		            }
						else{
							Toast.makeText(MainActivity.this, "最后一条", Toast.LENGTH_SHORT).show();
							lv.onRefreshComplete();
						}
					}
		        });  


				break;

			default:
				break;
			}

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

		// 找寻ID
		init();
		//开始初始化lv
	
		// 开始请求数据
		new Thread() {
			public void run() {
				try {

					getData(x);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		}.start();

	}
	private void init() {
		lv = (PullToRefreshListView) findViewById(R.id.lv);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void getData(int x) throws IOException {
		String dataFromUrl = Utils.getDataFromUrl(URL + x);
		Message msg = mHandler.obtainMessage();
		msg.obj = dataFromUrl;
		msg.what = 1;
		mHandler.sendMessage(msg);
	};
}
</span>


2.Utils工具类


<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * @author wj
 * @date 2016-7-28
 */
public class Utils {

	/**
	 * @param url
	 * @return 工具类
	 * @throws IOException
	 */
	public static String getDataFromUrl(String url) throws IOException {

		URL urlHttp = new URL(url);
		HttpURLConnection http = (HttpURLConnection) urlHttp.openConnection();
		http.setConnectTimeout(5000);
		http.setReadTimeout(5000);
		http.connect();
		byte[] by = new byte[1024];
		int len = -1;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int code = http.getResponseCode();
		InputStream stream = http.getInputStream();
		if (code == 200) {
			while ((len = stream.read(by)) != -1) {
				// 开始读取
				bos.write(by, 0, len);
			}
			return bos.toString("utf-8");
		}
		return null;
	}

	/**
	 * @param context
	 * @return 默认的imageLoder
	 */
	public static ImageLoader getImage(Context context) {
		ImageLoader image = ImageLoader.getInstance();
		image.init(ImageLoaderConfiguration.createDefault(context));
		return image;

	}
}
</span>


3.InfoBean实体类

<span style="font-size:18px;">import java.io.Serializable;

public class InfoBean implements Serializable{
/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
private String address;
private String default_image;
private String kaipan_new_date;
private String loupan_name;
private String new_price_value;
private String price;
private String region_title;
private String tags;
public String getAddress() {
	return address;
}
public void setAddress(String address) {
	this.address = address;
}
public String getDefault_image() {
	return default_image;
}
public void setDefault_image(String default_image) {
	this.default_image = default_image;
}
public String getKaipan_new_date() {
	return kaipan_new_date;
}
public void setKaipan_new_date(String kaipan_new_date) {
	this.kaipan_new_date = kaipan_new_date;
}
public String getLoupan_name() {
	return loupan_name;
}
public void setLoupan_name(String loupan_name) {
	this.loupan_name = loupan_name;
}
public String getNew_price_value() {
	return new_price_value;
}
public void setNew_price_value(String new_price_value) {
	this.new_price_value = new_price_value;
}
public String getPrice() {
	return price;
}
public void setPrice(String price) {
	this.price = price;
}
public String getRegion_title() {
	return region_title;
}
public void setRegion_title(String region_title) {
	this.region_title = region_title;
}
public String getTags() {
	return tags;
}
public void setTags(String tags) {
	this.tags = tags;
}
public static long getSerialversionuid() {
	return serialVersionUID;
}
public InfoBean(String address, String default_image, String kaipan_new_date, String loupan_name, String new_price_value, String price,
		String region_title, String tags) {
	super();
	this.address = address;
	this.default_image = default_image;
	this.kaipan_new_date = kaipan_new_date;
	this.loupan_name = loupan_name;
	this.new_price_value = new_price_value;
	this.price = price;
	this.region_title = region_title;
	this.tags = tags;
}
public InfoBean() {
	super();
}

}
</span>

4.实体类InfoList


<span style="font-size:18px;">import java.io.Serializable;

public class InfoList implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private InfoBean info;
	public InfoBean getInfo() {
		return info;
	}
	public void setInfo(InfoBean info) {
		this.info = info;
	}
	public InfoList(InfoBean info) {
		super();
		this.info = info;
	}
	public InfoList() {
		super();
	}
	
	

}
</span>

5.RowList实体类

<span style="font-size:18px;">import java.io.Serializable;
import java.util.ArrayList;

public class RowList implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ArrayList<InfoList> rows;

	public ArrayList<InfoList> getRows() {
		return rows;
	}

	public void setRows(ArrayList<InfoList> rows) {
		this.rows = rows;
	}

	public RowList(ArrayList<InfoList> rows) {
		super();
		this.rows = rows;
	}

	public RowList() {
		super();
	}

}
</span>


6.实体类ZongBean


<span style="font-size:18px;">import java.io.Serializable;

public class ZongBean implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private RowList result;

	public RowList getResult() {
		return result;
	}

	public void setResult(RowList result) {
		this.result = result;
	}

	public ZongBean() {
		super();
	}

	public ZongBean(RowList result) {
		super();
		this.result = result;
	}

}
</span>


7.activity_main.xml


<span style="font-size:18px;"><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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/lv"
      xmlns:ptr="http://schemas.android.com/apk/res-auto"  
        android:layout_height="fill_parent"  
        android:layout_width="fill_parent"  
        android:numColumns="auto_fit"  
        android:verticalSpacing="1dp"  
        android:horizontalSpacing="1dp"  
        android:columnWidth="100dp"  
        android:stretchMode="columnWidth"  
        android:gravity="fill"  
        ptr:ptrMode="both"    >
    </com.handmark.pulltorefresh.library.PullToRefreshListView>

</RelativeLayout></span>


8.lv_item.xml

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ima_item"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:text="张三"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv_addre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:text="张三"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="张三"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout></span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值