【Android】Web開發之通過標準Java接口處理Http請求

處理GET請求核心代碼

import java.net.*;import java.io.*;
URL url = "http://10.0.2.2/android/http_get.jsp?username=tom";
// 使用HttpURLConnection打開連接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// 得到讀取的內容(流)
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
// 爲輸出創建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
// 使用循環來讀取獲得的數據
while (((inputLine = buffer.readLine()) != null)) {
	resultData += inputLine + "\n";
}

處理POST請求核心代碼

HttpURLConnection urlConn = (HttpURLConnection) 
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");// 設置以POST方式
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
// 要上傳的參數
String content = "par=" + URLEncoder.encode("ABCDEFG中文", "UTF-8");
out.writeBytes(content);// 將要上傳的內容寫入流中
// 得到讀取的內容(流)
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
...//和GET等同

處理GET請求方法

發送GET請求並獲取服務器端返回值:
	public String handleGet(String strUrl) {
		try {
			URL url = new URL(strUrl);
			// 使用HttpURLConnection打開連接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();//打開到此 URL 引用的資源的通信鏈接
			// 得到讀取的內容(流)
			InputStream stream = conn.getInputStream();
			byte[] data = new byte[100*1024];
			int len = stream.read(data);
			result = new String(data, 0, len);
			result =  EncodingUtils.getString(result.getBytes(), "UTF-8");//編碼工具類解決中文亂碼
			conn.disconnect();//指示服務器近期不太可能有其他請求
			stream.close();
		} catch (Exception ee) {
			System.out.print("ee:" + ee.getMessage());
		}
		return result;
	}


處理POST請求方法

攜帶一個params數據發送Post請求到指Url:
	public String handlePost(String strUrl, String params) {
		try {
			URL url = new URL(strUrl);
			// 使用HttpURLConnection打開連接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");//設置 URL 請求的方法
			conn.setDoInput(true);//允許接收輸入
			conn.setDoOutput(true);//允許接收輸出
			//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.connect();//打開到此 URL 引用的資源的通信鏈接
			
			//用DataOutputStream.writeBytes(content)將請求參數寫入進去
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(params);
			dos.close();	
			
			try {
				//獲取該連接的輸入
				InputStream stream = conn.getInputStream();
				byte[] data = new byte[100* 1024];
				int len = stream.read(data);
				result = new String(data, 0, len);
				result =  EncodingUtils.getString(result.getBytes(), "UTF-8");
				conn.disconnect();//指示服務器近期不太可能有其他請求
				stream.close();
			} catch (Exception e) {
				System.out.print("e:" + e.getMessage());
			}
		} catch (Exception e) {
			System.out.print("e:" + e.getMessage());
		}
		return result;
	}

應用實例

爲了更加清晰的理解上述兩個方法,可通過下述實例進行練習。
【注】服務請求是應該寫在Handler中,配合線程一起使用的,在這裏爲了測試簡便而暫不使用。

Activity

package com.app.myweb;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * 範例:通過標準Java接口處理Http請求
 */
public class JavaHttp_JSP extends Activity implements OnClickListener {
	private TextView textView1, textView2;
	private Button button1, button2;
	private String result;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http_jsp);
		
		setUI(); setAction();
	}

	public void setUI() {
		textView1 = (TextView) findViewById(R.id.textView1);
		/*textView1.setText("利用Java標準接口java.net.*類實現讀取指定url內容");*/
		textView2 = (TextView) findViewById(R.id.textView2);
		
		button1 = (Button) findViewById(R.id.button1);
		button2 = (Button) findViewById(R.id.button2);
	}
	
	public void setAction() {
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
	}
	
	/** 發送GET請求並獲取服務器端返回值 */
	public String handleGet(String strUrl) {
		try {
			URL url = new URL(strUrl);
			// 使用HttpURLConnection打開連接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();//打開到此 URL 引用的資源的通信鏈接
			// 得到讀取的內容(流)
			InputStream stream = conn.getInputStream();
			byte[] data = new byte[100*1024];
			int len = stream.read(data);
			result = new String(data, 0, len);
			result =  EncodingUtils.getString(result.getBytes(), "UTF-8");//編碼工具類解決中文亂碼
			conn.disconnect();//指示服務器近期不太可能有其他請求
			stream.close();
		} catch (Exception ee) {
			System.out.print("ee:" + ee.getMessage());
		}
		return result;
	}

	/** 攜帶一個params數據發送Post請求到指Url */
	public String handlePost(String strUrl, String params) {
		try {
			URL url = new URL(strUrl);
			// 使用HttpURLConnection打開連接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");//設置 URL 請求的方法
			conn.setDoInput(true);//允許接收輸入
			conn.setDoOutput(true);//允許接收輸出
			//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.connect();//打開到此 URL 引用的資源的通信鏈接
			
			//用DataOutputStream.writeBytes(content)將請求參數寫入進去
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(params);
			dos.close();	
			
			try {
				//獲取該連接的輸入
				InputStream stream = conn.getInputStream();
				byte[] data = new byte[100* 1024];
				int len = stream.read(data);
				result = new String(data, 0, len);
				result =  EncodingUtils.getString(result.getBytes(), "UTF-8");
				conn.disconnect();//指示服務器近期不太可能有其他請求
				stream.close();
			} catch (Exception e) {
				System.out.print("e:" + e.getMessage());
			}
		} catch (Exception e) {
			System.out.print("e:" + e.getMessage());
		}
		return result;
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.button1:
			textView1.setText(handleGet("http://10.0.2.2:8888/android/1.jsp"));
			break;
		case R.id.button2:
			textView2.setText(handlePost("http://10.0.2.2:8888/android/2.jsp" , "username=tom&password=111"));
			break;
		default:
			break;
		}
	}
}

XML佈局文件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:text="接收GET請求" />

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="標準Java接口:發送GET請求" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:text="接收Post請求" />

        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="標準Java接口:發送POST請求" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:singleLine="false"
            android:text="" />
        
    </LinearLayout>

</ScrollView>


發佈了128 篇原創文章 · 獲贊 36 · 訪問量 85萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章