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

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

环境为:python

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

问题为:json

1.须要登陆才能够访问json数据,不然会提示权限不够api

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

1.第一次get请求登陆页,获得csrftoken服务器

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

3.访问json请求路径,其中请求头中设置csrftoken和sessionid,能够得到请求的数据session

好了,能够写代码了:app

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/

相关文章
相关标签/搜索