1、联系人表结构
添加一条联系人信息
package com.itheima.insertcontact;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
//1.在raw_contact表里面添加一条联系人的id
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Cursor cursor = getContentResolver().query(uri, new String[]{"_id"}, null, null, null);
cursor.moveToLast();
int _id = cursor.getInt(0);
int newid = _id+1;
ContentValues values = new ContentValues();
values.put("contact_id", newid);
getContentResolver().insert(uri, values);
//2.根据联系人的id 在 data表里面 添加对应的数据
Uri dataUri = Uri.parse("content://com.android.contacts/data");
//插入电话
ContentValues phoneValues = new ContentValues();
phoneValues.put("data1", "999999");
phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
phoneValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, phoneValues);
//插入邮箱
ContentValues emailValues = new ContentValues();
emailValues.put("data1", "zhaoqi@itheima.com");
emailValues.put("mimetype", "vnd.android.cursor.item/email_v2");
emailValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, emailValues);
//插入姓名
ContentValues nameValues = new ContentValues();
nameValues.put("data1", "zhaoqi");
nameValues.put("mimetype", "vnd.android.cursor.item/name");
nameValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, nameValues);
}
}
读取联系人
package com.itheima.readcontacts.service;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.itheima.readcontacts.domain.ContactInfo;
public class ContactInfoService {
/**
* 获取手机里面全部的联系人信息
* @return
*/
public static List<ContactInfo> getContactInfos(Context context){
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
List<ContactInfo> contactInfos = new ArrayList<ContactInfo>();
Cursor cursor = resolver.query(uri, new String[]{"contact_id"}, null, null, null);
while(cursor.moveToNext()){
String contact_id = cursor.getString(0);
System.out.println("联系人id:"+contact_id);
//根据联系人的id 查询 data表里面的数据
Cursor dataCursor = resolver.query(dataUri, new String[]{"data1","mimetype"}, "raw_contact_id=?", new String[]{contact_id}, null);
ContactInfo contactInfo = new ContactInfo();
while(dataCursor.moveToNext()){
String data1 = dataCursor.getString(0);
String mimetype = dataCursor.getString(1);
if("vnd.android.cursor.item/phone_v2".equals(mimetype)){
contactInfo.setPhone(data1);
}else if("vnd.android.cursor.item/email_v2".equals(mimetype)){
contactInfo.setEmail(data1);
}else if("vnd.android.cursor.item/name".equals(mimetype)){
contactInfo.setName(data1);
}
}
dataCursor.close();
contactInfos.add(contactInfo);
}
cursor.close();
return contactInfos;
}
}
2、从Internet获取数据
利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);//设置连接超时
conn.setRequestMethod(“GET”);//以get方式发起请求
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg");
public static void readAsFile(InputStream inSream, File file) throws Exception{
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
outStream.close();
inSream.close();
}
3、向Internet发送请求参数
String requestUrl = "http://localhost:8080/itcast/contanctmanage.do";
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("age", "12");
requestParams.put("name", "中国");
StringBuilder params = new StringBuilder();
for(Map.Entry<String, String> entry : requestParams.entrySet()){
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
params.append("&");
}
if (params.length() > 0) params.deleteCharAt(params.length() - 1);
byte[] data = params.toString().getBytes();
URL realUrl = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);//发送POST请求必须设置允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data);
outStream.flush();
if( conn.getResponseCode() == 200 ){
String result = readAsString(conn.getInputStream(), "UTF-8");
outStream.close();
System.out.println(result);
}
4、向Internet发送xml数据
利用HttpURLConnection对象,我们可以向网络发送xml数据.
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<M1 V=10000>");
xml.append("<U I=1 D=\"N73\">中国</U>");
xml.append("</M1>");
byte[] xmlbyte = xml.toString().getBytes("UTF-8");
URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5* 1000);
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(xmlbyte);//发送xml数据
outStream.flush();
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//获取返回数据
String result = readAsString(is, "UTF-8");
outStream.close();
5、网络图片查看器
package com.ithiema.newimageviewer;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int GET_IMAGE_SUCCESS = 1;
protected static final int SERVER_ERROR = 2;
protected static final int LOAD_IMAGE_ERROR = 3;
private ImageView iv_icon;
private EditText et_path;
/**
* 在主线程创建一个消息处理器
*/
private Handler handler = new Handler(){
//处理消息的 运行在主线程里面
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case GET_IMAGE_SUCCESS:
Bitmap bm = (Bitmap) msg.obj;
iv_icon.setImageBitmap(bm);
break;
case SERVER_ERROR:
Toast.makeText(MainActivity.this, "连接服务器错误", 0).show();
break;
case LOAD_IMAGE_ERROR:
Toast.makeText(MainActivity.this, "获取图片错误", 0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_icon = (ImageView) findViewById(R.id.iv_icon);
et_path = (EditText) findViewById(R.id.et_path);
getMainLooper();
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空", 0).show();
return;
} else {
new Thread() {
public void run() {
// 以httpget的方式 请求数据.获取图片的流
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 设置请求方式
conn.setRequestMethod("GET");
// 设置连接超时时间
conn.setConnectTimeout(3000);
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)");
// 获取服务器端返回的状态码
int code = conn.getResponseCode();
if (code == 200) {
// 获取服务器端返回的流
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
//iv_icon.setImageBitmap(bitmap);
//不可以直接更新界面,发送消息更新界面
Message msg = new Message();
msg.obj = bitmap;
msg.what = GET_IMAGE_SUCCESS;
handler.sendMessage(msg);
} else {
//Toast.makeText(MainActivity.this, "连接服务器错误", 0).show();
Message msg = new Message();
msg.what = SERVER_ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getApplicationContext(), "获取图片失败", 0).show();
Message msg = new Message();
msg.what = LOAD_IMAGE_ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
}
6、HTML源代码查看器
package com.itheima.htmlviewer;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int GET_HTML_FINISH = 1;
protected static final int LOAD_ERROR = 2;
private TextView tv_html;
private EditText et_path;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case GET_HTML_FINISH:
String html = (String) msg.obj;
tv_html.setText(html);
break;
case LOAD_ERROR:
Toast.makeText(getApplicationContext(), "获取html失败", 0).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_html = (TextView) findViewById(R.id.tv_html);
et_path = (EditText) findViewById(R.id.et_path);
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空", 0).show();
} else {
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len =0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
String html = new String(bos.toByteArray(),"gbk");
Message msg = new Message();
msg.what = GET_HTML_FINISH;
msg.obj = html;
handler.sendMessage(msg);
}else{
Message msg = new Message();
msg.what = LOAD_ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = new Message();
msg.what = LOAD_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
};
}.start();
}
}
}
7、模拟网络登录
package com.itheima.login;
import com.itheima.login.service.LoginService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
/**
* activity 实际上是上下文的一个子类
* @author Administrator
*
*/
public class MainActivity extends Activity {
protected static final int LOGIN = 1;
protected static final int ERROR = 2;
private EditText et_username;
private EditText et_password;
private CheckBox cb_remeber_pwd;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case LOGIN:
String info = (String) msg.obj;
Toast.makeText(getApplicationContext(),info, 0).show();
break;
case ERROR:
Toast.makeText(getApplicationContext(), "连接网络失败...", 0).show();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb_remeber_pwd = (CheckBox) findViewById(R.id.cb_remeber_pwd);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
try {
String result = LoginService.readUserInfoFromFile(this);
String[] infos = result.split("##");
et_username.setText(infos[0]);
et_password.setText(infos[1]);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 登陆按钮的点击事件
* @param view
*/
public void login(View view){
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){
Toast.makeText(getApplicationContext(), "用户名或者密码不能为空", 0).show();
return;
}
//检查是否勾选了cb
if(cb_remeber_pwd.isChecked()){//记住密码
try {
LoginService.saveUserInfoToFile(this, username, password);
Toast.makeText(this, "保存用户名密码成功", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "保存用户名密码失败", 0).show();
}
}
new Thread(){
public void run() {
//登陆到服务器,发送一个httpget的请求
try {
String result = LoginService.loginByHttpClientPost(username, password);
Message msg = new Message();
msg.what = LOGIN;
msg.obj = result;
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
package com.itheima.login.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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.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.content.Context;
import com.itheima.login.utils.StreamUtils;
/**
* 登陆相关的服务
*
* @author Administrator
*
*/
public class LoginService {
// 上下文 其实提供了应用程序 的一个详细的环境信息. 包括 包名是什么 /data/data/目录在哪里.
// we do chicken right
/**
* 保存用户信息到文件
*
* @param username
* 用户名
* @param password
* 密码
*/
public static void saveUserInfoToFile(Context context, String username,
String password) throws Exception {
// File file = new File("/data/data/com.itheima.login/info.txt");
// File file = new File(context.getFilesDir(),"info.txt"); //在当前应用程序的目录下
// 创建一个files目录 里面有一个文件 info.txt
// FileOutputStream fos = new FileOutputStream(file);
FileOutputStream fos = context.openFileOutput("info.txt",
Context.MODE_PRIVATE);// 追加模式
// zhangsan##123456
fos.write((username + "##" + password).getBytes());
fos.close();
}
/**
* 读取用户的用户名和密码
*
* @return // zhangsan##123456
*/
public static String readUserInfoFromFile(Context context) throws Exception {
File file = new File(context.getFilesDir(), "info.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = br.readLine();
fis.close();
br.close();
return line;
}
/**
* 采用http的get方式提交数据到服务器
*
* @return
*/
public static String loginByHttpGet(String username, String password)
throws Exception {
// http://localhost:8080/web/LoginServlet?username=zhangsan&password=123
String path = "http://192.168.1.100:8080/web/LoginServlet?username="
+ URLEncoder.encode(username, "UTF-8") + "&password="
+ URLEncoder.encode(password, "utf-8");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 把is里面的内容转化成 string文本.
String result = StreamUtils.readStream(is);
return result;
} else {
return null;
}
}
/**
* 采用http的post方式提交数据到服务器
*
* @return
*/
public static String loginByHttpPost(String username, String password)
throws Exception {
// 1.提交的地址
String path = "http://192.168.1.100:8080/web/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 2.请求方式
conn.setRequestMethod("POST");
// 准备数据
// username=zhangsan&password=123
String data = "username=" + URLEncoder.encode(username, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
// 3.注意:一定要设置请求头参数
// 设置数据是一个form表单的类型
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setConnectTimeout(5000);
// 4.post请求实际上是把数据以流的方式写给了服务器
// 设置允许通过http请求向服务器写数据
conn.setDoOutput(true);
// 得到一个向服务写数据的流
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 把is里面的内容转化成 string文本.
String result = StreamUtils.readStream(is);
return result;
} else {
return null;
}
}
public static String loginByHttpClientGet(String username, String password)
throws Exception {
// 1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
// 2.输入地址
String path = "http://192.168.1.100:8080/web/LoginServlet?username="
+ URLEncoder.encode(username, "UTF-8") + "&password="
+ URLEncoder.encode(password, "utf-8");
HttpGet httpGet = new HttpGet(path);
// 3.敲回车
HttpResponse response = client.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
// 把is里面的内容转化成 string文本.
String result = StreamUtils.readStream(is);
return result;
}else{
return null;
}
}
/**
* 采用httpclient的post方式提交数据到服务器
* @param username
* @param password
* @return
* @throws Exception
*/
public static String loginByHttpClientPost(String username, String password)
throws Exception {
// 1.打开一个浏览器
HttpClient client = new DefaultHttpClient();
// 2.输入地址
String path = "http://192.168.1.100:8080/web/LoginServlet";
HttpPost httpPost = new HttpPost(path);
//设置要提交的数据实体
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"UTF-8");
httpPost.setEntity(entity);
// 3.敲回车
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
// 把is里面的内容转化成 string文本.
String result = StreamUtils.readStream(is);
return result;
}else{
return null;
}
}
}
package com.itheima.login.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamUtils {
/**
* 用默认码表转化一个inputstream里面的内容 到 字符串
* @param is
* @return
*/
public static String readStream(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
is.close();
return new String(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
8、SmartImageView网络图片查看器
package com.ithiema.newimageviewer;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int GET_IMAGE_SUCCESS = 1;
protected static final int SERVER_ERROR = 2;
protected static final int LOAD_IMAGE_ERROR = 3;
private ImageView iv_icon;
private EditText et_path;
/**
* 在主线程创建一个消息处理器
*/
private Handler handler = new Handler(){
//处理消息的 运行在主线程里面
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case GET_IMAGE_SUCCESS:
Bitmap bm = (Bitmap) msg.obj;
iv_icon.setImageBitmap(bm);
break;
case SERVER_ERROR:
Toast.makeText(MainActivity.this, "连接服务器错误", 0).show();
break;
case LOAD_IMAGE_ERROR:
Toast.makeText(MainActivity.this, "获取图片错误", 0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_icon = (ImageView) findViewById(R.id.iv_icon);
et_path = (EditText) findViewById(R.id.et_path);
getMainLooper();
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径不能为空", 0).show();
return;
} else {
new Thread() {
public void run() {
// 以httpget的方式 请求数据.获取图片的流
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 设置请求方式
conn.setRequestMethod("GET");
// 设置连接超时时间
conn.setConnectTimeout(3000);
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Shuame)");
// 获取服务器端返回的状态码
int code = conn.getResponseCode();
if (code == 200) {
// 获取服务器端返回的流
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
//iv_icon.setImageBitmap(bitmap);
//不可以直接更新界面,发送消息更新界面
Message msg = new Message();
msg.obj = bitmap;
msg.what = GET_IMAGE_SUCCESS;
handler.sendMessage(msg);
} else {
//Toast.makeText(MainActivity.this, "连接服务器错误", 0).show();
Message msg = new Message();
msg.what = SERVER_ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(getApplicationContext(), "获取图片失败", 0).show();
Message msg = new Message();
msg.what = LOAD_IMAGE_ERROR;
handler.sendMessage(msg);
}
};
}.start();
}
}
}
9、AsyncHttp登录
package com.itheima.login;
import java.net.URLEncoder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
/**
* activity 实际上是上下文的一个子类
*
* @author Administrator
*
*/
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
/**
* GET登陆按钮的点击事件
*
* @param view
*/
public void login(View view) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "用户名或者密码不能为空", 0).show();
return;
}
String path = "http://192.168.1.100:8080/web/LoginServlet?username="
+ URLEncoder.encode(username) + "&password="
+ URLEncoder.encode(password);
AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
Toast.makeText(getApplicationContext(), response, 0).show();
}
});
}
/**
* POST登陆按钮的点击事件
*
* @param view
*/
public void postLogin(View view) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "用户名或者密码不能为空", 0).show();
return;
}
String path = "http://192.168.1.100:8080/web/LoginServlet";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(getApplicationContext(), content, 0).show();
}
});
}
}