android学习二:http

</pre>想自己搭建服务器进行按并且进行网络的编程。先了解一下http。http的get和post的一些区分及概念请参照:<a target=_blank target="_blank" href="http://blog.csdn.net/csj50/article/details/5687850">http://blog.csdn.net/csj50/article/details/5687850</a><p></p><p>还有这篇文章是通过看 <老罗的视频> 了解来的。</p><p></p><p>自己的感觉就是网络上的资源都自己的地址(网址),通过编程连接这个网址就是相当于操作电脑上的文件一样。这种方式就是GET。还有post的是要发送数据。一般都是</p><p>发送我要获取什么的数据。比如id,名字等。</p><h1>一、Get功能的实现。</h1><p><span style="white-space:pre"></span></p><p>在eclipse(j2ee)里面新建一个myhttp的动态web工程,在WebContent文件夹里面新建一个jsp文件为index.jsp。这个index.jsp就是入口程序。</p><p>在WebContent里面增加一张图片2.png。点击run on server 或者在浏览器输入网址 http://localhost/myhttp/2.png则可以得到这个图片。</p><p>比如说我们在浏览器上面输入 http://c11.eoemarket.com/app0/403/403225/screen/2157036.jpg 也能够得到一张图片。这个图片是在其他人的服务器上面的。</p><p>知道了服务器地址后我们如何通过get进行获取这张图片。</p><p>1、URL url =  new URL(URL_PATH);  //path就是上面的网址</p><p>2、  httpURLConnection = (HttpURLConnection) url.openConnection();</p><p><span style="white-space:pre"></span>httpURLConnection.setConnectTimeout(3000); //设置参数</p><p><span style="white-space:pre"></span>httpURLConnection.setDoInput(true); //向服务器获取数据</p><p><span style="white-space:pre"></span>httpURLConnection.setDoOutput(true);//向服务器发送数据 POST方法需要用到 这里可以不用</p><p><span style="white-space:pre"></span>httpURLConnection.setRequestMethod("GET"); //GET方法</p><p> 3  查看返回码,这个比URLConnection多的函数</p><p><span style="white-space:pre"></span>int responseCode = httpURLConnection.getResponseCode();  //阻塞到成功或者异常</p><p>4  如果正确则 返回输入流 inputStream = httpURLConnection.getInputStream();</p><p>5  通过inputStream 读取内容。可以通过FileOutputStream 保存到文件。</p><p></p><p></p><pre name="code" class="java">public class HttpUtils {
	private static String URL_PATH = "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1210/26/c0/14689467_1351240945864_800x600.jpg";
	public HttpUtils() {}
	public static void saveImageToDisk() {
		InputStream inputStream = getInputStream();
		if (inputStream == null) {
			System.out.println("inputStream = null");
			return;
		}
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			// 下面这句话调用后如果没有文件就已经会创建一个文件了
			fileOutputStream = new FileOutputStream("C:\\test.png");
			while ((len = inputStream.read(data)) != -1) {
				// 将指定 byte数组中从偏移量0开始的 len个字节写入此文件输出流
				fileOutputStream.write(data, 0, len);
			}
		} catch (Exception e) {
		} finally {
<span style="white-space:pre">			</span>try{
			<span style="white-space:pre">	</span>inputStream.close();
			<span style="white-space:pre">	</span>fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	
	public static InputStream getInputStream() {
		InputStream inputStream = null;
		HttpURLConnection httpURLConnection = null;
		try {
			URL url = new URL(URL_PATH);
			if (url != null) {
				System.out.println("0");
				httpURLConnection = (HttpURLConnection) url.openConnection();
				// 设置连接网络的超时时间
				httpURLConnection.setConnectTimeout(3000);
				httpURLConnection.setDoInput(true);
				// 表示设置本次http请求使用GET方式请求
				httpURLConnection.setRequestMethod("GET");
				System.out.println("4");
				int responseCode = httpURLConnection.getResponseCode(); // 如过超时或者其他异常
				System.out.println("responseCode = " + responseCode);
				if (responseCode == 200) {
					// 从服务器获得一个输入流
					inputStream = httpURLConnection.getInputStream();
				}
			}
		} catch (MalformedURLException e) {
			System.out.println("e1 = " + e);

		} catch (IOException e) {
			System.out.println("e2 = " + e);
			e.printStackTrace();
		}
		return inputStream;
	}

	public static void main(String[] args) {
		// 从服务器获得图片保存到本地
		saveImageToDisk();
	}
}



二、下面讲一下post功能。

1、服务器的功能就是要实现一个登录的界面。通过post把用户名和密码发去服务器响应。返回注册成功与失败的情况。

常规我们在浏览器里面输入网址http://127.0.0.1/myhttp/ 出现一个表格。可以输入用户名和密码,点击提交后通过LoginAction判断结果。
还有就是通过编程连接 http://127.0.0.1/myhttp/LoginAction,得到urlConnection,通过outputstream提交 “username=xx&password=xxxxx”进行验证。


(一)、先讲服务端的
下面是index.jsp。只是一个表格,填写了用户名和密码后就会发送到/LoginAciton响应。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath(); //
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试HTTP协议体的内容</title>
</head>
<body>
	<form name="form1"  method="post" action="<%=path %>/LoginAction">
			用户名:
			<input type="text" name="username" value="" />
			<br />
			密  码:
			<input type="password" name="password" value="" />
			<br />
			<input type="submit" name="submit" value="提交表单" />
	</form>
</body>
</html>
必要的说明

<%
String path = request.getContextPath(); //这里是获取路径 即path = http://localhost/myhttp
%>

action="<%=path %>/LoginAction" 表示提交后的响应的sevlet
在源码的位置新建一个sevlet叫做LoginAction.java 开头有  @WebServlet("/LoginAction") 表示这个sevlet的路径是 /LoginAction。

两个响应的函数

doget

dopost 函数

/LoginAction 代码如下。

@WebServlet("/LoginAction")
public class LoginAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginAction() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		System.out.println("-username->>"+username);
		String pswd = request.getParameter("password");
		System.out.println("-password->>"+pswd);
		if(username.equals("admin")&&pswd.equals("123")){
			out.print("login is success!!!!");
		}else{
			out.print("login is fail!!!");
		}
		out.flush();
		out.close();
	}

	@Override
	public void destroy() {
		super.destroy();
	}
	
	@Override
	public void init() throws ServletException {
		super.init();
	}
	
}


下面前4句是固定的,第五句是例子

response.setContentType("text/html;charset=utf-8");//设置的一些东西编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();//输出到网页的流
String username = request.getParameter("username");//获取参数等

(二)、客服端的程序。

跟Get的步骤基本类似

1、URL url =  new URL(URL_PATH);  //path就是上面的网址

2、  httpURLConnection = (HttpURLConnection) url.openConnection();

httpURLConnection.setConnectTimeout(3000); //设置参数

httpURLConnection.setDoInput(true); //向服务器获取数据

httpURLConnection.setDoOutput(true);//向服务器发送数据 POST方法需要用到 这里可以不用

httpURLConnection.setRequestMethod("POST"); //GET方法

在这里插入post的数据 如 :

byte[] mydata = "username=admin&password=123".toString().getBytes();
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(mydata,0,mydata.length);
outputStream.close();

 3  查看返回码,这个比URLConnection多的函数

int responseCode = httpURLConnection.getResponseCode();  //阻塞到成功或者异常

4  如果正确则 返回输入流 inputStream = httpURLConnection.getInputStream();

5  通过inputStream 读取内容。可以通过FileOutputStream 保存到文件。



























































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值