Django REST Framework学习——Android使用REST方法访问Diango

本文更应该叫做Android如何模拟浏览器访问Django服务器后台。

环境为:

Android通过HttpClient访问服务器,从Django中获取json数据,解析显示在UI界面上。

问题为:

1.需要登录才可以访问json数据,否则会提示权限不够

登录,也就是把用户名和密码放在请求的参数中呗,但是问题是其中会包含一个csrftoken个东西,问题就不好玩了。每次访问登录界面,都会由服务器生成一个csrftoken,放在浏览器的cookie中,登录动作中,服务器会校验cookie中的csrftoken,同时验证用户名和密码,如果验证通过,则将sessionid和csrftoken再次返回给浏览器,设置在cookie中,访问json中的数据时,会同时检验sessionid和csrftoken,那问题就简单了,可以分成这么几步在做:

1.第一次get请求登录页,得到csrftoken

2.设置用户名,密码,cookie中的csrftoken,(其实还包括更用户名密码类似的csrfmiddlewaretoken,next参数),post请求验证,得到sessionid

3.访问json请求路径,其中请求头中设置csrftoken和sessionid,可以获得请求的数据

好了,可以写代码了:

1.定义变量

String url = "http://ipaddress:8004/api-auth/login/?next=/";//第一次get请求url
String url2 = "http://ipaddress:8004/api-auth/login/";//第二次登录验证url
DefaultHttpClient httpClient;

public static String sessionID = "";
public static String scrftoken = "";

private HttpResponse mHttpResponse = null;
String htmlText;//返回的结果

Context context;

2.第一次请求,得到csrftoken

httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpGet(new URI(url1)));

//这里通过cooki获得,其实也可以在网页中解析csrfmiddlewaretoken获得,值是一样的
CookieStore cookieStore = httpClient.getCookieStore();
List<Cookie> cookies = cookieStore.getCookies();

String csrftoken = null;
for (Cookie cookie : cookies) {
    if (cookie.getName().equals("csrftoken")) {
        csrftoken = cookie.getValue();
    }
}
Log.i("get csrftoken", csrftoken);

3.第二次请求得到sessionid

HttpPost post = new HttpPost(new URI(url2));
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
// 设置登陆信息
BasicNameValuePair csrfmiddlewaretoken2 = new BasicNameValuePair("csrfmiddlewaretoken", csrftoken);
//如果通过验证,接下来的路径,在未登录情况下访问数据,提示没有权限时
//在不同界面登录这个值可能不同,不过关系不大,这里忽略,设置成默认的/
BasicNameValuePair next = new BasicNameValuePair("next", "/");
BasicNameValuePair username = new BasicNameValuePair("username", "renyuzhuo");
BasicNameValuePair password = new BasicNameValuePair("password", "renyuzhuo");
//这个值没用
BasicNameValuePair login = new BasicNameValuePair("submit", "Log in");
// 设置发送数据
paramList.add(csrfmiddlewaretoken2);
paramList.add(next);
paramList.add(username);
paramList.add(password);
paramList.add(login);

post.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));
//这句话是关键,在请求头中设置csrftoken,也有设置成X-CRFSToken的,这里不做测试了
//需要看Django
post.setHeader(new BasicHeader("csrftoken", csrftoken));

httpClient.setCookieStore(cookieStore);
mHttpResponse = httpClient.execute(post);
if (mHttpResponse.getStatusLine().getStatusCode() == 200) {
htmlText = EntityUtils.toString(mHttpResponse.getEntity(), "utf-8");
Message message = new Message();
message.what = 0;
message.obj = htmlText;
Log.i("html", htmlText);

CookieStore cookieStore2 = httpClient.getCookieStore();
List<Cookie> cookies2 = cookieStore2.getCookies();
for (Cookie cookie : cookies2) {
Log.i("cookie::", cookie.getName() + " " + cookie.getValue());
//这里重复设置了csrftoken,没什么必要,写成token=csrftoken就可以了
        if (cookie.getName().equals("csrftoken")) {
csrftoken = cookie.getValue();
}
        //获取sessionid
if (cookie.getName().equals("sessionid")) {
sessionID = cookie.getValue();
}
}

}

4.访问json数据:

//设置json数据的url0
HttpGet get = new HttpGet(new URI(URLS.xxxx));
get.setHeader(new BasicHeader("csrftoken", csrftoken));
get.setHeader(new BasicHeader("sessionid", sessionID));
HttpResponse response = httpClient.execute(get);
Log.i("code::", response.getStatusLine().getStatusCode() + "");
if (response.getStatusLine().getStatusCode() == 200) {
htmlText = EntityUtils.toString(response.getEntity(), "utf-8");
Log.i("html", htmlText);
}

Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);

常见的403错误往往就是请求头设置出错,也就是加红的部分

5.获取了json数据,接下来的操作就不在本文包含的范围内了。

附核心源码:http://files.cnblogs.com/files/renyuzhuo/DjangoLogin.zip

知其所以然:

csrftoken是什么:

Cross-site request forgery,跨站请求伪造,就是其他网站伪造请求,达到攻击的目的,你说说我这上面的代码方式是不是就是一个伪造请求呢,也算是一种攻击吧,不过我的目的仅仅是因为服务器没有给我预留接口,我就只能这样了。如果是一个循环,必定是一个不会造成什么严重后果的攻击。

Django REST Framework是什么:

基于Django的REST框架,是一个轻量级的库,可以很容易构建WEB API,被设计成模块化,易用于自定义的体系结构,基于Django的基础类视图。python,Django

Django是什么:

官网宣传标语:Django makes it easier to build better Web apps more quickly and with less code.

官网的解释:Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

 

下面的链接对你可能有帮助:

403错误:http://stackoverflow.com/a/17283820/440489

CSRF介绍:http://drops.wooyun.org/papers/155

Django REST Framework官网:http://www.django-rest-framework.org/

原文地址:https://www.cnblogs.com/renyuzhuo/p/5031296.html