天天看點

Android之使用URLConnection進行網絡程式設計

使用URLConnection進行網絡程式設計~

       URL的openConnection()方法将傳回一個URLConnection,該對象表示應用程式和URL之間的通信連接配接,程式可以通過URLConnection執行個體向該URL發送請求,讀取URL引

用的資源。通常建立一個和URL的連接配接,并發送請求,讀取此URL引用的資源。

需要如下步驟:

  a)通過調用URL對象openConnection()方法來

    建立URLConnection對象

  b)設定URLConnection的參數和普通請求屬性

    conn.setRequestProperty("accept","*/*");

    conn.setRequestProperty("connection","Keep-Alive");

    conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    //發送POST請求必須設定如下兩行

    conn.setDoInput(true):設定該URLConnection的doInput請求頭字段的值

    coon.setDoOutput(true):

  c)調用connect():打開到此URL引用的資源的通信連結(如果尚未建立這樣的連接配接)。

    如果在已打開連接配接(此時 connected 字段的值為 true)的情況下調用 connect 方法,則忽略該調用.

    URLConnection 對象經曆兩個階段:首先建立對象,然後建立連接配接。

        在建立對象之後,建立連接配接之前,可指定各種選項(例如doInput和UseCaches).連接配接後再進行設定就會發生錯誤。連接配接後才能進行的操作(例如getContentLength),如有必要,将隐式執行連接配接.

  d)如果隻是發送GET方式請求,使用connect方法建立和遠端資源之間的實際連接配接即可,在請求的位址中傳入資料。

  如果需要發送Post方法請求。需要擷取

  URLConnection執行個體對應的輸出流來發送請求參數,

     PrintWriter out=new PrintWriter(conn.getOutputStream());

     //解決亂碼問題

     String n=EncodingUtils.getString("張三".getBytes(),"UTF-8");

     out.write("name="+n+"&pwd="+pwd);

     out.flush();//重新整理輸出流的緩沖

  e)遠端資源變為可用,程式可以通路遠端資源的頭字段或通過輸入流讀取遠端資源的資料。

      getInputStream()擷取輸入流。

      從輸入流讀取response的資料。

注意:1)如果既要使用輸入流讀取URLConnection響應的内容,也要使用輸出流發送請求參數,一定要先使用輸出流,再使用輸入流。

        2)借助于URLConnection類的幫助,應用程式可以非常友善地與指定站點交換資訊,包括發送GET請求,POST請求,并擷取網站的響應等。

代碼編寫步驟如下:

1.先寫一個伺服器-web工程

建立一個Servlet--LoginServlet,簡單實作使用者的登入~

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

   
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		System.out.println(name+"   "+pwd);
		OutputStream os=response.getOutputStream();
		if("xuxu".equals(name)&&"123".equals(pwd)){
			os.write(("成功").getBytes("UTF-8"));
		}else{
			os.write(("失敗").getBytes("UTF-8"));
		}
		os.flush();
		os.close();
	}

}
           

2.建立一個android項目,在MainActivity中分别使用get方法和post方法實作使用者的登入

public class MainActivity extends Activity {

	private EditText name,pwd;
	public void get(View view){
		new Thread(){
			public void run() {
				try {
					URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"+
				"?name="+name+"&pwd="+pwd);
					URLConnection conn=url.openConnection();
					conn.connect();//真正的建立網絡連接配接
					BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line=null;
					StringBuffer stringBuffer=new StringBuffer();//字元串,都可以存儲和操作字元串,它是變量
					while ((line=reader.readLine())!=null) {
						stringBuffer.append(line);
					}
					System.out.println(stringBuffer.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	public void post(View view){
		new Thread(){
			public void run() {
				try {
					URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"
				);
					URLConnection conn=url.openConnection();
					//必須設定
					conn.setDoInput(true);
					conn.setDoOutput(true);
					
					conn.connect();//真正的建立網絡連接配接
					
					PrintWriter printWriter=new PrintWriter(conn.getOutputStream());
					
					printWriter.write("name="+name+"&pwd="+pwd);
					printWriter.flush();
					printWriter.close();
					
					BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line=null;
					StringBuffer stringBuffer=new StringBuffer();
					while ((line=reader.readLine())!=null) {
						stringBuffer.append(line);
					}
					System.out.println(stringBuffer.toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		name=(EditText) findViewById(R.id.name);
		pwd=(EditText) findViewById(R.id.pwd);
	}

	
}
           

3.運作,把Tomcat打開~

效果圖如下:

Android之使用URLConnection進行網絡程式設計

想要伺服器和源碼的:http://download.csdn.net/detail/qq_33642117/9583776