android 网络
Android  /  houtizong 发布于 3年前   148
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;@Overrideprotected 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() {@Overridepublic 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;@Overrideprotected 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;@Overrideprotected 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() {@Overridepublic 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();// 设置请求方式为Postconn.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;@Overrideprotected 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() {@Overridepublic 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();}}};}
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接