您的位置:首页 > 理论基础 > 计算机网络

HttpClient+DL

2016-01-25 14:25 477 查看
package com.baidu.httpurlconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import com.bwie.helper.MyHelper;
import com.bwie.vo.News;
import com.bwie.vo.SuperNews;
import com.google.gson.Gson;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
public static final String LOGIN_URL = "http://101.200.142.201:8080/tqyb/login";
private static final String LOGIN_NEWS_URL = "http://101.200.142.201:8080/tqyb/newsList.json";
private EditText ed_name;
private EditText ed_pwd;
// 创建handler
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
// 创建线程
new Thread() {
public void run() {
// 从服务器得到json串
String str = getJsonFromServer();
perseJson(str);
System.out.println(str);
}

}.start();
startActivity(new Intent(MainActivity.this, NewActivity.class));
}
};
};

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

}

private void init() {
ed_name = (EditText) findViewById(R.id.name);
ed_pwd = (EditText) findViewById(R.id.pwd);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {

private String ename;
private String epwd;

public void onClick(View v) {
ename = ed_name.getText().toString();
epwd = ed_pwd.getText().toString();
// 开启线程
new Thread() {
public void run() {
String data = getDataByServerByGet(ename, epwd);
if (data.equals("success")) {
handler.sendMessage(handler.obtainMessage(1, data));
}
}

}.start();
}
});
}

private void perseJson(String str) {
// TODO Auto-generated method stub
Gson g = new Gson();
SuperNews superNews = g.fromJson(str, SuperNews.class);
// 创建实体类集合
// List<News> list = new ArrayList<News>();
List<News> list = superNews.getList().getArticles();
// 添加到数据库,以便查询
MyHelper helper = new MyHelper(MainActivity.this, "qqqqqqqqqq", null, 1);
SQLiteDatabase database = helper.getWritableDatabase();
// 添加得使用循环
// db.execSQL("create table news (id integer,title varchar(200),litpic varchar(100),typeid varchar(10),description varchar(800),url description(100))");

for (News n : list) {
database.execSQL("insert into news values(null,?,?,?,?,?)",
new String[] { n.getTitle(), n.getLitpic(), n.getTypeid(),
n.getDescription(), n.getUrl() });
}

}

private String getJsonFromServer() {
// TODO Auto-generated method stub
String str = "";
// 创建路径
try {
URL url = new URL(LOGIN_NEWS_URL);
// 打开
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
// 设置时间
openConnection.setConnectTimeout(5000);
openConnection.setReadTimeout(5000);
// 得到IO流
InputStream is = openConnection.getInputStream();
int length = is.available();
byte[] buffer = new byte[length];
is.read(buffer);
str = new String(buffer, 0, length);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
};

private String getDataByServerByGet(String ename, String epwd) {
// TODO Auto-generated method stub
String rs = "";
// 创建StringBuffer
StringBuffer sb = new StringBuffer(LOGIN_URL);
// 追加用户名和密码
sb.append("?username=" + ename);
sb.append("&userpass=" + epwd);
try {
// 创建url路径
URL url = new URL(sb.toString());
// 打开
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
// 设置时间
openConnection.setConnectTimeout(5000);
openConnection.setReadTimeout(5000);
// 判断是否成功
if (openConnection.getResponseCode() == 200) {
// 创建IO流对象
BufferedReader br = new BufferedReader(new InputStreamReader(
openConnection.getInputStream(), "utf-8"));
rs = br.readLine();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: