您的位置:首页 > 理论基础 > 计算机网络

Android中解析网络请求的URL

2014-11-06 16:38 337 查看
最近正在做Android网络应用的开发,使用了android网络请求方面的知识,现在向大家介绍网络请求方面的知识,我们知道android中向服务器端发送一个请求,(这就是我们通常所说的POST请求),我们要发送一个完整的URL,然后服务器端接收到这个URL,对这个URL进行特定的解析,就是对URL进行解析,转化为JSON数据,然后,我们只要处理这个JSON数据就可以了。



我现在就用我的项目实例来体现解析URL的过程:

1、组装URL的过程:

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,

这实际上是一个比较清晰的流程,其中也可以看出多线程处理的模式。

一旦我们需要网络请求的时候,我们一般会将网络请求的处理部分放在子线程中,另外开一个线程,这样就不会在原线程中处理过多的事情,这也减轻了主线程的压力。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: