android 网络

android的网络编程和java的一样没什么好分析的都是一些死的照着写就可以了,所以记录下来  方便查找   ,  服务器使用的是TomCat

 

服务器代码;  servlet的使用需要在xml中注册

package servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.Music;

/**
 * Servlet implementation class MusicServlet
 */
public class MusicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		
		// 获得客户端提交的参数,获取客户端的参数
		String flag = request.getParameter("flag");
		//将字符串的字符集由Iso8859-1 转为 UTF-8
		//flag = new String(flag.getBytes("ISO8859-1"),"UTF-8");
		System.out.println("请求的:"+flag);

		// 链接数据库,查询数据
		ArrayList<Music> list = new ArrayList<Music>();
		for (int i = 0; i < 10; i++) {
			Music m = new Music();
			m.setName("歌曲" + i);
			m.setGeshou("歌手" + i);
			m.setSize("5:2" + i);
			m.setZhuanji("专辑" + i);
			list.add(m);
		}
                  //将数据放在队列中
		request.setAttribute("list", list);

		if (flag.equals("xml")) {
			request.getRequestDispatcher("xml.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("json.jsp").forward(request, response);	
		}
	}

}

java bean 

package pojo;

public class Music {

	private String name;
	private String geshou;
	private String size;
	private String zhuanji;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGeshou() {
		return geshou;
	}

	public void setGeshou(String geshou) {
		this.geshou = geshou;
	}

	public String getSize() {
		return size;
	}

	public void setSize(String size) {
		this.size = size;
	}

	public String getZhuanji() {
		return zhuanji;
	}

	public void setZhuanji(String zhuanji) {
		this.zhuanji = zhuanji;
	}

}

 

xml格式显示

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="java.util.*,pojo.*"%>

<%
	//取数据
    ArrayList<Music> list = (ArrayList<Music>)request.getAttribute("list");
    if(list!=null){//如果list存在,就将队列中的数据包装成xml格式的数据输出
%>
	<?xml version='1.0' encoding='UTF-8'?>
	<musiclist>

 <%
 	for(int i=0;i<list.size();i++){
 		Music m = list.get(i);
 %> 
 	<music>
 		<name><%=m.getName() %></name>
 		<geshou><%=m.getGeshou() %></geshou>
 		<zhuanji><%=m.getZhuanji() %></zhuanji>
 		<size><%=m.getSize() %></size>
 	</music>
 <%
 	}
 %>
 </musiclist>
  <%
 	}
 %>

 

json格式显示

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ page import="java.util.*,pojo.*"%>

<%
	//取数据
    ArrayList<Music> list = (ArrayList<Music>)request.getAttribute("list");
    if(list!=null){//如果list存在,就将队列中的数据包装成xml格式的数据输出
%>
	<?xml version='1.0' encoding='UTF-8'?>
	<musiclist>

 <%
 	for(int i=0;i<list.size();i++){
 		Music m = list.get(i);
 %> 
 	<music>
 		<name><%=m.getName() %></name>
 		<geshou><%=m.getGeshou() %></geshou>
 		<zhuanji><%=m.getZhuanji() %></zhuanji>
 		<size><%=m.getSize() %></size>
 	</music>
 <%
 	}
 %>
 </musiclist>
  <%
 	}
 %>

 

 

 

android格式端 访问服务器

 

1,访问图片  输入图片的地址  点击按钮获取图片

public class SecondActivity extends Activity {

	private EditText pathView;
	private ImageView imgView;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_second);
		pathView = (EditText) this.findViewById(R.id.pathView);

		imgView = (ImageView) this.findViewById(R.id.imgView);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 100:
					Bitmap bmp = (Bitmap) msg.obj;
					imgView.setImageBitmap(bmp);
					break;

				default:
					break;
				}
			}
		};

	}

	public void connServer(View v) {
		// 获取地址.地址必须是http开头的
		String path = pathView.getText().toString().trim();

		if (!path.startsWith("http://")) {
			path = "http://" + path;
		}

		new MyThread(path).start();

	}

	class MyThread extends Thread {
		String path;

		public MyThread(String path) {
			this.path = path;
		}

		public void run() {
			try {
				// 要请求的Uri地址
				URL url = new URL(path);
				// 通过URL建立一个连接
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				// 设置请求方式
				conn.setRequestMethod("GET");
				// 设置超时时间
				conn.setConnectTimeout(5000);

				// 获得输入流
				InputStream ips = conn.getInputStream();

				// 定义一个字节数组输出流
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				// 读取一个字节
				int t = ips.read();
				while (t != -1) {
					// 将读取到的直接写到字节数组输出流
					bos.write(t);
					// 读取下一个字节
					t = ips.read();
				}

				// 将字节数组输出流中的字节写入数组
				byte[] bs = bos.toByteArray();

				// 通过字节数组创建一个图片对象
				Bitmap bmp = BitmapFactory.decodeByteArray(bs, 0, bs.length);

				Message msg = handler.obtainMessage(100);
				msg.obj = bmp;
				handler.sendMessage(msg);

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

	};

}

 

 

 

2,基于http的post和get请求

public class ClientActivity extends Activity {

	private EditText pathView;
	private TextView imgView;
	private Handler handler;

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

		pathView = (EditText) this.findViewById(R.id.pathView);
		imgView = (TextView) this.findViewById(R.id.imgView);

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 100:
					String str = (String) msg.obj;
					imgView.setText(str);
					break;

				}

			}
		};

	}

	public void connServer(View v) {
		// 要请求的地址
		String path = pathView.getText().toString().trim();
		if (!path.startsWith("http://")) {
			path = "http://" + path;
		}

		new MyThreadPost(path).start();

	}

	// 基于HttpClient发送Get请求
	class MyThread extends Thread {

		String path;

		public MyThread(String path) {
			this.path = path;
		}

		public void run() {
			try {
				// 定义客户端对象
				HttpClient client = new DefaultHttpClient();
				// 定义要发送的请求对象
				HttpGet get = new HttpGet(path);
				// 发送请求,返回响应对象
				HttpResponse response = client.execute(get);
				// 如果响应成功
				if (response.getStatusLine().getStatusCode() == 200) {
					// 获得返回的数据
					HttpEntity entity = response.getEntity();
					String str = EntityUtils.toString(entity);

					Message msg = handler.obtainMessage(100);
					msg.obj = str;

					handler.sendMessage(msg);
				}

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

	// 基于HttpClient发送Post请求
	class MyThreadPost extends Thread {
		String path;

		public MyThreadPost(String path) {
			this.path = path;
		}

		public void run() {
			try {
				// 定义客户端对象
				HttpClient client = new DefaultHttpClient();
				// 包装Post请求对象
				HttpPost post = new HttpPost(path);
				// 数据源
				ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>();
				NameValuePair nvp = new BasicNameValuePair("flag", "xml");
				nvpList.add(nvp);

				// 定义要提交的数据实体
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvpList);
				// 设置要提交的数据
				post.setEntity(entity);

				// 发送请求
				HttpResponse response = client.execute(post);

				if (response.getStatusLine().getStatusCode() == 200) {
					// 获得返回的数据
					HttpEntity entity2 = response.getEntity();
					String str = EntityUtils.toString(entity2);

					Message msg = handler.obtainMessage(100);
					msg.obj = str;

					handler.sendMessage(msg);
				}

			} catch (Exception ef) {
				ef.printStackTrace();
			}

		}
	}

}

 

 

3,HttpURLConnection 的post请求

public class PostActivity extends Activity {

	private EditText pathView;
	private TextView imgView;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_xml);
		pathView = (EditText) this.findViewById(R.id.pathView);

		imgView = (TextView) this.findViewById(R.id.imgView);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 100:
					byte[] bs = (byte[]) msg.obj;
					String str = new String(bs);
					imgView.setText(str);

					break;

				default:
					break;
				}
			}
		};

	}

	public void connServer(View v) {
		// 获取地址.地址必须是http开头的
		String path = pathView.getText().toString().trim();

		if (!path.startsWith("http://")) {
			path = "http://" + path;
		}

		new MyThread(path).start();

	}

	class MyThread extends Thread {
		String path;

		public MyThread(String path) {
			this.path = path;
		}

		public void run() {
			try {
				
				// 要请求的Uri地址
				URL url = new URL(path);
				// 通过URL建立一个连接
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				// 设置请求方式为Post
				conn.setRequestMethod("POST");
				// 设置超时时间
				conn.setConnectTimeout(5000);
				//设置允许输出数据
				conn.setDoOutput(true);
				
				//准备要发送的数据
				String data = "flag=张三";
				
				//定义Post方式的数据标头
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", ""+data.getBytes().length);

				//获得输出流,写出数据
				OutputStream ops = conn.getOutputStream();
				ops.write(data.getBytes());
				ops.flush();
				ops.close();
				
		System.out.println("conn.getResponseCode()"+conn.getResponseCode());
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					// 获得输入流
					InputStream ips = conn.getInputStream();

					// 定义一个字节数组输出流
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					// 读取一个字节
					int t = ips.read();
					while (t != -1) {
						// 将读取到的直接写到字节数组输出流
						bos.write(t);
						// 读取下一个字节
						t = ips.read();
					}

					// 将字节数组输出流中的字节写入数组
					byte[] bs = bos.toByteArray();

					Message msg = handler.obtainMessage(100);
					msg.obj = bs;
					handler.sendMessage(msg);
				} else {
					Message msg = handler.obtainMessage(100);
					msg.obj = "响应失败!".getBytes();
					handler.sendMessage(msg);

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

	};

}

 

4,HttpURLConnection 的get请求

public class XMLActivity extends Activity {

	private EditText pathView;
	private TextView imgView;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_xml);
		pathView = (EditText) this.findViewById(R.id.pathView);

		imgView = (TextView) this.findViewById(R.id.imgView);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 100:
					byte[] bs = (byte[]) msg.obj;
					String str = new String(bs);
					imgView.setText(str);

					break;

				default:
					break;
				}
			}
		};

	}

	public void connServer(View v) {
		// 获取地址.地址必须是http开头的
		String path = pathView.getText().toString().trim();

		if (!path.startsWith("http://")) {
			path = "http://" + path;
		}

		new MyThread(path).start();

	}

	class MyThread extends Thread {
		String path;

		public MyThread(String path) {
			this.path = path;
		}

		public void run() {
			try {
				//获得参数
				String arg  = path.substring(path.lastIndexOf("=")+1);
				//对参数的值进行编码
				arg = URLEncoder.encode(arg, "UTF-8");
				//先截取掉原来的参数值,在加上编码后的参数值
				path= path.substring(0,path.lastIndexOf("=")+1)+arg;
				System.out.println(">>>>>>>>>"+path);
				// 要请求的Uri地址
				URL url = new URL(path);
				// 通过URL建立一个连接
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				// 设置请求方式
				conn.setRequestMethod("GET");
				// 设置超时时间
				conn.setConnectTimeout(5000);

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					// 获得输入流
					InputStream ips = conn.getInputStream();

					// 定义一个字节数组输出流
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
					// 读取一个字节
					int t = ips.read();
					while (t != -1) {
						// 将读取到的直接写到字节数组输出流
						bos.write(t);
						// 读取下一个字节
						t = ips.read();
					}

					// 将字节数组输出流中的字节写入数组
					byte[] bs = bos.toByteArray();

					Message msg = handler.obtainMessage(100);
					msg.obj = bs;
					handler.sendMessage(msg);
				} else {
					Message msg = handler.obtainMessage(100);
					msg.obj = "响应失败!!";
					handler.sendMessage(msg);

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

	};

}

 

你可能感兴趣的:(网络)