安卓 http 编程 笔记

模板文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
	<TextView
	    android:id="@+id/tv_user"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="用户名"
	    />
	<EditText
	    android:id="@+id/et_user"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="请填写用户名"
	    />
	<TextView
	    android:id="@+id/tv_pass"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="密码"
	    />
	<EditText
	    android:id="@+id/et_pass"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:hint="请填写密码"
	    />
	<Button
	    android:id="@+id/button"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="get登录"
	    android:onClick="getLogin"
	    />
	<Button
	    android:id="@+id/button2"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="post登录"
	    android:onClick="postLogin"
	    />
	<Button
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="httpClientGet登录"
	    android:onClick="clientGetLogin"
	    />
	<Button
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="httpClientPost登录"
	    android:onClick="clientPostLogin"
	    />
</LinearLayout>

MainActivity

package com.http.action;

import com.login.service.LoginService;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	protected static final int LOGIN_SUCCESS = 1;
	protected static final int LOGIN_ERROR = 2;
	private EditText et_user;
	private EditText et_pass;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message message)
		{
			switch (message.what) {
				case LOGIN_SUCCESS:
					Toast.makeText(MainActivity.this, (String) message.obj, Toast.LENGTH_SHORT).show();
					break;
				case LOGIN_ERROR:
					Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
					break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et_user = (EditText) findViewById(R.id.et_user);
		et_pass = (EditText) findViewById(R.id.et_pass);
	}

	/**
	 * 登录
	 * @param view
	 */
	public void getLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.byGetLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	/**
	 * post 方式提交
	 * @param view
	 */
	public void postLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String text = LoginService.byPostLogin(user, pass);
				if (text != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = text;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	/**
	 * client get login
	 * @param view
	 */
	public void clientGetLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.httpClientGetLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}

	/**
	 * client post login
	 * @param view
	 */
	public void clientPostLogin(View view)
	{
		final String user = et_user.getText().toString().trim();
		final String pass = et_pass.getText().toString().trim();
		new Thread(){
			public void run()
			{
				String res = LoginService.httpClientPostLogin(user, pass);
				if (res != null) {
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					msg.obj = res;
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = LOGIN_ERROR;
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
}

LoginService

package com.login.service;

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.util.ArrayList;
import java.util.List;

import org.apache.http.HttpConnection;
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 com.stream.utils.Stream;

public class LoginService
{
	/**
	 * 通过get方式提交
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String byGetLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass;
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			System.out.println(code);
			if (code == 200) {
				InputStream is = conn.getInputStream();
				String text = Stream.isToString(is);
				return text;
			} else {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通过post方式提交
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String byPostLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php";
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			String data = "user="+user+"&pass="+pass;
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", data.length()+"");
			conn.setDoOutput(true);
			OutputStream os = conn.getOutputStream();
			os.write(data.getBytes());
			int code = conn.getResponseCode();
			if (code == 200) {
				InputStream is = conn.getInputStream();
				return Stream.isToString(is);
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 采用httpclient get 提交
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String httpClientGetLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(path);
			HttpResponse response = client.execute(get);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String text = Stream.isToString(is);
				return text;
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * httpClient post 方式提交
	 * @param user
	 * @param pass
	 * @return
	 */
	static public String httpClientPostLogin(String user, String pass)
	{
		String path = "http://192.168.0.105/index.php";
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(path);
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("user", user));
		parameters.add(new BasicNameValuePair("pass", pass));
		try {
			post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
			HttpResponse response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream is = response.getEntity().getContent();
				String text = Stream.isToString(is);
				return text;
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}

stream 把 输入流转换成字符串

package com.stream.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Stream
{
	/**
	 * 把一个输入流变成字符串
	 * @param is
	 * @return
	 * @throws IOException
	 */
	static public String isToString(InputStream is) throws IOException
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		byte[] buffer = new byte[1024];
		while ((len = is.read(buffer)) != -1) {
			baos.write(buffer);
		}
		byte[] result = baos.toByteArray();
		is.close();
		baos.close();
		return new String(result);
	}
}

切记清单文件权限

<uses-permission android:name="android.permission.INTERNET"/>

时间: 2024-11-06 09:29:56

安卓 http 编程 笔记的相关文章

安卓权威编程-笔记(19章 使用SoundPool播放音频)

针对BeatBox应用,可以使用SoundPool这个特别定制的实用工具. SoundPool能加载一批声音资源到内存中,并支持同时播放多个音频文件.因此所以,就算用户兴奋起来,狂按按钮播放全部音频,也不必担心会损坏应用或者耗光手机电量. 1. 创建SoundPool 1 /* 2 * Lollipop引入了新的方式创建SoundPool:使用SoundPool.Builder.为了兼容api 16最低级别,只能选择使用SoundPool(int int int)这个老构造方法. 3 * 第一个

安卓第八天笔记--网络编程二

安卓第八天笔记--网络编程二 1.网络图片查看器 /** * 网络图片查看器 * 1.获取输入的URL地址,判断是否为空 * 2.建立子线程,获取URl对象new URL(path) * 3.打开连接获取HttpURLConnection conn = (HttpURLConnection) url.openConnection(); * 4.设置连接超时时间conn.setConnectionTimeOut(5000)毫秒 * 5.设置请求方式setRequestMethod * GET或者P

站在.NET的角度学安卓的草民笔记1

Java           ->        .NET 安卓          ->        winform/WPF 类继承Activity  ->     类继承 Form ①安卓的 如果android中你有2个Activity,可以从一个Activity跳到另一个Activity怎么搞 Intent t=new Intent(MainActivity.this,OtherActivity.class); startActivity(t); 使用Intent,专业术语叫 意图

安卓第二天笔记-数据保存

安卓第二天笔记--数据保存 1.保存数据私有文件 <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&

python核心编程--笔记

python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗余输出(导入语句详细追踪) 1.5 –m mod 将一个模块以脚本形式运行 1.6 –Q opt 除法选项(参阅文档) 1.7 –c cmd 运行以命令行字符串心事提交的python脚本 1.8 file   以给定的文件运行python脚本 2 _在解释器中表示最后

安卓开发复习笔记——Fragment+FragmentTabHost组件(实现新浪微博底部菜单)

记得之前写过2篇关于底部菜单的实现,由于使用的是过时的TabHost类,虽然一样可以实现我们想要的效果,但作为学习,还是需要来了解下这个新引入类FragmentTabHost 之前2篇文章的链接: 安卓开发复习笔记——TabHost组件(一)(实现底部菜单导航) 安卓开发复习笔记——TabHost组件(二)(实现底部菜单导航) 关于Fragment类在之前的安卓开发复习笔记——Fragment+ViewPager组件(高仿微信界面)也介绍过,这里就不再重复阐述了. 国际惯例,先来张效果图: 下面

C++windows内核编程笔记day07_day08,可视化建菜单、加速键使用、绘图等

可视化操作创建的菜单,加载到窗口. 方法1:注册时指定菜单 wce.lpszMenuName=MAKEINTRESOURCE(IDR_MENUMAIN);//数字形式的资源ID转换为字符串形式的资源 方法2: //创建窗口时加载菜单资源 HMENU menumain= LoadMenu(g_hinstance,MAKEINTRESOURCE(IDR_MENUMAIN)); menumain 传入 CreateWindowEx();//倒数第三个参数 窗口指定小图标: 1.注册时指定 wce.hI

C++windows内核编程笔记day09_day10,对话框和窗口基本控件等的使用

//设置字体颜色 SetTextColor(hdc,RGB(255,0,0)); //窗口背景 //wce.hbrBackground=(HBRUSH)(COLOR_WINDOW+1); //wce.hbrBackground=CreateSolidBrush(RGB(0,0,255)); //设置字体背景 SetBkColor(hdc,RGB(0,0,200)); //设置字体背景模式 SetBkMode(hdc,TRANSPARENT);//字体背景透明 //创建字体,成功返回字体,失败返回

安卓第一天笔记

安卓第一天笔记 1.移动通信的发展G--(generation) 1G:模拟制式 2G:GSM/CDMA 2.5G:GPRS 2.75G:EDGE 3G:WCDMA/CDMA2000/TD-SCDMA 3.5G/3.75G:HSDPA/HSUPA/HSDPA+ 4G:TD-LTE( Long term evolution)长期演进 GSM:9K -->GPRS:42K--> EDGE:172K -->WCDMA:364k -->HSDPA/HSUPA:14.4M -->HSD