Android使用Http协议操作网络资源

版权声明:有问题可联系博主QQ:15577969,大家一起相互交流和学习。 https://blog.csdn.net/qq15577969/article/details/80895050

1、AndroidManifest.xml清单文件需要给网络权限


2、MainActivity.java

package com.t20.netword;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
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 LOGIN_MSG = 0;
	private EditText etName;
	private EditText etPwd;
	private ImageView ivPic;
	/**
	 * 句柄
	 */
	private Handler handler=new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what) {
			case LOGIN_MSG:
				String message=(String) msg.obj;
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		etName=(EditText) findViewById(R.id.etName);
		etPwd=(EditText) findViewById(R.id.etPassword);
		ivPic=(ImageView) findViewById(R.id.ivPic);
		
		//使用xUtils框架的BitmapUtils加载网络图片
		BitmapUtils bu=new BitmapUtils(this);
		String uri="http://172.168.40.32:8088/AndroidService/pic.jpg";
		bu.display(ivPic, uri);
	}
	/**
	 * 使用xUtils框架进行get提交
	 * @param v
	 */
	public void xUtils_get_submit(View v){
		HttpUtils hu=new HttpUtils();
		String name=etName.getText().toString();
		String pwd=etPwd.getText().toString();
		String url="http://172.168.40.32:8088/AndroidService/LoginServlet?name="+name+"&pwd="+pwd;
		hu.send(HttpMethod.GET, url,  new RequestCallBack<String>(){

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// TODO Auto-generated method stub
				String message=responseInfo.result;
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();							
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				// TODO Auto-generated method stub
				Log.e("xUtils错误信息", msg);
			}
			
		});
	}
	/**
	 * 使用xUtils框架进行post提交
	 * @param v
	 */
	public void xUtils_post_submit(View v){
		HttpUtils hu=new HttpUtils();
		String name=etName.getText().toString();
		String pwd=etPwd.getText().toString();
		String url="http://172.168.40.32:8088/AndroidService/LoginServlet";
		RequestParams params=new RequestParams();
		//使用键值对方式传参数
		params.addBodyParameter("name", name);
		params.addBodyParameter("pwd", pwd);
		hu.send(HttpMethod.POST, url, params, new RequestCallBack<String>(){

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// TODO Auto-generated method stub
				String message=responseInfo.result;
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();							
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				// TODO Auto-generated method stub
				Log.e("xUtils错误信息", msg);
			}
			
		});
	}
	/**
	 * 安卓原生态提交方式
	 * @param v
	 */
	public void submit(View v){
		
		//开子线程(连接网络等耗时操作都 不建议在主线程里运行,因此最好开子线程来完成 )
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				BufferedReader reader=null;
				HttpURLConnection conn=null;
				try {
					String name=etName.getText().toString();
					String pwd=etPwd.getText().toString();
					//1.准备需要访问的网址
					URL url=new URL("http://172.168.40.32:8088/AndroidService/LoginServlet?name="+name+"&pwd="+pwd);
					//2.创建连接
					conn= (HttpURLConnection) url.openConnection();
					//3.设置提交方式
					conn.setRequestMethod("GET");
					//4.设置链接超时时间(防卡顿)
					conn.setConnectTimeout(8000);
					//5.设置读取超时时间
					conn.setReadTimeout(8000);
					
					//获取响应码
					int code=conn.getResponseCode();
					if(code==200){
						//6.提交请求,获取信息流
						InputStream is=conn.getInputStream();
						//7.从信息流中获取信息
						reader=new BufferedReader(new InputStreamReader(is));
						StringBuilder sb=new StringBuilder();
						String line;
						while ((line=reader.readLine())!=null) {
							sb.append(line)	;			
						}						
		//-----------------------------	Handler机制------------------------------------//			
						//【Handler机制】1.创建消息
						Message message= Message.obtain();
						//【Handler机制】2.设置消息类型
						message.what=LOGIN_MSG;
						//【Handler机制】3.设置消息内容
						message.obj=sb.toString().trim();
						//【Handler机制】4.发送消息
						handler.sendMessage(message);
		//----------------------------------------------------------------------------//					
					}else if(code==404)	{
						Log.i("接收到的消息:", "404");
					}else if(code==500)	{
						Log.i("接收到的消息:", "500");
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					try {
						//关闭资源
						if(reader!=null){
							reader.close();
						}
						if(conn!=null){
							conn.disconnect();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq15577969/article/details/80895050