Android中解析網絡請求的URL

最近正在做Android網絡應用的開發,使用瞭android網絡請求方面的知識,現在向大傢介紹網絡請求方面的知識,我們知道android中向服務器端發送一個請求,(這就是我們通常所說的POST請求),我們要發送一個完整的URL,然後服務器端接收到這個URL,對這個URL進行特定的解析,就是對URL進行解析,轉化為JSON數據,然後,我們隻要處理這個JSON數據就可以瞭。

我現在就用我的項目實例來體現解析URL的過程:

1、組裝URL的過程:vcD4KPHA+PHByZSBjbGFzcz0=”brush:java;”>private String getOrderPayUrl(int order, int action, String accountid,
String token) {
Calendar calendar = Calendar.getInstance();
long time = calendar.getTimeInMillis() / 1000;
return orderPayUrl + “?action=” + action + “&time=” + time
+ “&accountid=” + accountid + “&token=” + token + “&paymoney=”
+ order + “¤cy=CNY&” + “sign=”
+ getSign(action, time, accountid);
}

2、發送URL的過程:

private void httpRequest(String url, int which, String method) {
		HttpRequestTask task = new HttpRequestTask(mHandler, url, which, method);
		task.startTask();
	}

其中mHandler為一個定義的局部變量,用Handler類型來處理返回的解析結果,

public class HttpRequestTask implements Runnable {

	private Handler handler;
	private String url;
	private int which;
	private String method;

	public HttpRequestTask(Handler handler, String url, int which, String method) {
		this.url = url;
		this.handler = handler;
		this.which = which;
		this.method = method;

	}

	public void startTask() {
		new Thread(this).start();
	}

	@Override
	public void run() {
		Looper.prepare();
		sendRequest();
	}

	private void sendRequest() {
		String result = null;
		if (method != null && method.equals(MyConstant.POST)) {
			result = HttpUtil.queryStringForPost(url);
		}
		if (method != null && method.equals(MyConstant.GET)) {
			result = HttpUtil.queryStringForGet(url);
		}
		// Log.e("---result---", result);
		Message msg = Message.obtain();
		msg.what = which;
		msg.obj = result;
		handler.sendMessage(msg);
	}

}

3、解析URL的過程:

// 發送Post請求,獲得響應查詢結果
	public static String queryStringForPost(String url) {

		HttpPost request = HttpUtil.getHttpPost(url);
		String result = null;

		try {
			// 獲得響應對象
			HttpResponse response = HttpUtil.getHttpResponse(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity());
				return result;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result = "網絡異常!";
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			result = "網絡異常!";
			return result;
		}
		return result;
	}

// // 獲得post請求對象request
	public static HttpPost getHttpPost(String url) {
		// 去除空格
//		if (url != null) {
//			Pattern p = Pattern.compile("\\s");
//			Matcher m = p.matcher(url);
//			url = m.replaceAll("");
//		}
		HttpPost request = new HttpPost(url);
		return request;
	}

其中我們要使用的包文件是

org.apache.http.client.methods.HttpPost

實際上返回的result字符串是一個JSON類型的字符串,我們隻需要使用JSONObject來處理相應的JSON就可以瞭,得到我們需要數據,返回,OK,

這實際上是一個比較清晰的流程,其中也可以看出多線程處理的模式。

一旦我們需要網絡請求的時候,我們一般會將網絡請求的處理部分放在子線程中,另外開一個線程,這樣就不會在原線程中處理過多的事情,這也減輕瞭主線程的壓力。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *