架构技术

联系我们

架构技术

当前位置:主页 > 架构技术 >

Android通过get,post方式体访问http服务器

发布时间:2019-01-28 编辑:环亚

RT..我之前感觉Android网络通信很神奇,Magic...最近学习了网络知识,现在来总结一下怎么做

好了,就拿例子来说明原理.

说下这个Demo的用处:

1.用户可以访问一个网页

2.用户提交用户名和密码到Http服务器中,在Tomcat的控制台中显示出提交的内容.

先来介绍一下怎么访问网页

看代码

package com.hwb.service;

import java.net.HttpURLConnection;
import java.net.URL;

import com.hwb.utils.StringReader;


public class HtmlContentService
{
    /**
     * 根据路径去获得数据
     * @param path 访问的路径
     * @return 结果
     * @throws Exception
     */
    public static byte[] getContent(String path) throws Exception
    {
        URL url = new URL(path);//构建一个URL对象
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//得到链接对象
        httpURLConnection.setRequestMethod("POST");//设置请求方法
        httpURLConnection.setReadTimeout(5000);///设置超时时间
        if(httpURLConnection.getResponseCode()==200)//获得响应码
        {
          
            byte[] arr = new byte[1024];
            int res = -1;
            while((res = in.read(arr)) != -1)
            {
                byteArrayOutputStream.write(arr, 0,res);
            }
            byteArrayOutputStream.close();
            in.close();
            return byteArrayOutputStream.toByteArray();
            
        }
        return null ;
    }
}



通过这个简单的方法我们就能进行一次http请求,请求结果可以先读取成二进制数据,然后在进行相应的操作,例如,我们可以获得某个网站的源码之类的..

在应用中,我们可能会从http服务器返回一个xml文件或者是json格式的字符串,我们都可以通过这种方式获得二进制数据,然后进行相应数据的处理

好了,现在介绍下通过get,post提交数据到http服务器

首先我们需要一个http服务器,我拿Tomcat来说明,首先建立一个简单的web application.

看看这个servliet吧..

package com.hwb.control;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 *  
 * @ProjectName:  [webProvider] 
 * @Package:      [com.hwb.control]  
 * @ClassName:    [UserServlet]   
 * @Author:       [hwb]   
 * @CreateDate:   [2014-6-7 下午4:15:57]   
 * @UpdateUser:   [hwb]   
 * @UpdateDate:   [2014-6-7 下午4:15:57]   
 * @UpdateRemark: [说明本次修改内容]  
 * @Version:      [v1.0]
 */
public class UserServlet extends HttpServlet
{
	/**
	 *接受2个参数,在控制台打印出来 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{

		String name = request.getParameter("name");
		String password = request.getParameter("password");
		System.out.println("name =" + name + ",password = "+ password);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request,response);
	}
}


好了,我们建立一个Android应用

我建的是4.4的

现在只看关键代码

package com.hwb.service;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class UserService
{
	/**
	 *  一个简单扼方法通过get方式提交数据到http服务器上
	 * @param path 访问的url
	 * @param userName 上传的用户名
	 * @param passWord 密码
	 * @return 上传成功与否
	 */
	public static boolean sendDataByGet(String path, String userName,String passWord)
	{
		try
		{
			StringBuilder stringBuilder = new StringBuilder(path);
			//进行编码  
			stringBuilder.append("?name=").append(URLEncoder.encode(userName,"UTF-8")).append("&password=").append(URLEncoder.encode(passWord,"UTF-8"));
			
			URL url = new URL(stringBuilder.toString());
			HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setConnectTimeout(5000);
			if(httpURLConnection.getResponseCode()==200)
			{
				return true;
			}
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 
	 * @param path 路径
	 * @param userName 用户名
	 * @param passWord  密码
	 * @return 结果
	 */
	public static boolean sendDataByPost(String path, String userName,String passWord)
	{
		try
		{
		    URL url = new URL(path);
		    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		    
		    StringBuilder builder = new StringBuilder();
		    builder.append("name=").append(URLEncoder.encode(userName,"UTF-8")).append("&password=").append(URLEncoder.encode(passWord,"UTF-8"));
		    byte[] arr = builder.toString().getBytes();
		    httpURLConnection.setRequestMethod("POST");
		    httpURLConnection.setConnectTimeout(5000);
		    httpURLConnection.setDoOutput(true);//设置可以写数据
		    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置http post请求的头部信息 请求数据内容类型
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(arr.length));//设置http post请求的头部信息请求数据的长度
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(arr);//往数据流中写数据
			
		    if(httpURLConnection.getResponseCode()==200)
		    {
		    	return true;
		    }
		    
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}


从中我学到了几个知识点,现在总结一下

1.首先是GET和POST请求的差别.大家都知道GET是在URL路径后面跟上参数,而POST则是放在了请求体内.我用了一个简单的工具拦截了请求,大家可以看看这个比较

vcD4KPHA+usPBy6OstNPV4ry4t/nNvM7Sw8fWqrXAwcvSu9Cp1qrKtrXjus294r72tcSw7LeoLsrXz8jkr8DAxve74bDvztLDx7bUyv2+3b340NCx4MLrLsbktM6jrHBvc3TKx7K7ysew0cr9vt23xdTazbeyv7XEPC9wPgo8cD66w8HLz9bU2r3ivvax4MLrzsrM4qOsvMjIu87Sw8fWqrXAwcvkr8DAxve74bDvztLDx7HgwuujrMTHw7TO0sPHzqrBy8ihtcPK/b7dvs3Q6NKqvfjQ0M/g06a1xL3iwusuPC9wPgo8cD7O0sPHz8jG1byw0rvPwtK70KnWqsq2teOjrMi7uvPU2su1PC9wPgo8cD7O0r+0wcvV4saqzsTVwqOs1/a49rzytaW1xNChveEuPC9wPgo8cD621EdFVLe9yr3AtMu1o6zkr8DAxvfX7tbVysfS1Glzbzg4NTktMbXEt73Kvczhvbu1vbf+zvHG97XEo6y82cnoztK1xLf+zvHG98rHVE9NQ0FUo6zL/MSsyM+1xLHgwuu3vcq90rLKx0lTTzg4NTktMaOsyOe5+87Sw8fWsb3Tzai5/XJlcXVlc3QuZ2V0UGFyYW1ldGVyKCk7IMC0u/G1w8r9vt2jrM35zfm74cLSwuujrMbk1K3S8r7NysfO0sPHzOG9u7XEyrG68r/JxNzPyNPDVVRGLTi78tXfR0JLtcS3vcq9z8i9+NDQseDC6y4uveK+9re9t6i+zcrHv8nS1NC0uPax4MLruf3Cy8b3o6zXqMPFzqpHRVTH68fzuf3Cyy7Ew87StcRERU1PwLTLtaOsztK1xL/Nu6e2y9PDVVRGLTi1xLe9yr3AtLHgwuujrMTHw7TO0r7Nv8nS1NXiw7TX9jwvcD4KPHByZSBjbGFzcz0="brush:java;">new String(value.getBytes("ISO-8859-1"),"UTF-8");具体代码看下面

现在讲讲post方式,我们可以直接指定编码方式就可以获取正确的数据了

好了,看看所有的代码

package com.hwb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter
{

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException
	{
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = (HttpServletRequest)arg0;
		HttpServletResponse httpServletResponse = (HttpServletResponse)arg1;
		String method = httpServletRequest.getMethod();
		if(method.equals("GET"))
		{
			EncodingWrap encodingWrap = new EncodingWrap(httpServletRequest);
			arg2.doFilter(encodingWrap, httpServletResponse);
		}
		else if(method.equals("POST"))
		{
			httpServletRequest.setCharacterEncoding("UTF-8");//必须设置编码方式
			arg2.doFilter(httpServletRequest, httpServletResponse);
		}
	}
}

package com.hwb.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EncodingWrap extends HttpServletRequestWrapper
{
	public EncodingWrap(HttpServletRequest request)
	{
		super(request);
	}

	@Override
	public String getParameter(String name)
	{
		// TODO Auto-generated method stub
		
		if(name==null)
			return null;
		else 
		{
			String value = super.getParameter(name);
			try
			{
				return new String(value.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return  null;
	}

}



好了,大致就是这样了,不正确请指出!


--------------------------------------------------------------

如果是上传文件的话,最好用socket做,因为http服务器对请求数据文件大小有限制

http://www.bkjia.com/Androidjc/781330.htmlwww.bkjia.comtruehttp://www.bkjia.com/Androidjc/781330.htmlTechArticleRT..我之前感觉Android网络通信很神奇,Magic...最近学习了网络知识,现在来总结一下怎么做 好了,就拿例子来说明原理. 说下这个Demo的用处...

本文源自: AG环亚官网


Copyright © 2005-2016 http://www.aayipanthi.com AG环亚官网_环亚AG娱乐_AG环亚集团_腾讯体育版权所有 AG环亚官网_环亚AG娱乐_AG环亚集团_腾讯体育