Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android通過get,post方式體訪問http服務器

Android通過get,post方式體訪問http服務器

編輯:關於Android編程

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則是放在了請求體內.我用了一個簡單的工具攔截了請求,大家可以看看這個比較

\

\

\

那麼中文怎麼辦呢?

請看GET

\

請看post

\


<喎?/kf/ware/vc/" target="_blank" class="keylink">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服務器對請求數據文件大小有限制

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved