I need to write a client that uses session cookies in Java for Android to use. I think I got the hang of writing Android apps, but when looking for a library to use for REST apis I only found very, very low level APIs - which is fine, but I don't understand it.
I have this in python requests, which I need to convert into Java/Android.
import requests;
import json;
s = requests.Session()
headers = {
'Host': 'REMOVED',
'Accept': '*/*',
'Content-Type': 'application/json',
'Accept-Language': 'en-US;q=1',
'User-Agent': 'REMOVED',
}
data = '{"username":"???","language":0,"password":"???"}'
s.post('REMOVED', headers=headers, data=data)
headers = {
'Host': 'REMOVED',
'Proxy-Connection': 'keep-alive',
'Accept': '*/*',
'Content-Type': 'application/json',
'Accept-Language': 'en-US;q=1',
'User-Agent': 'REMOVED',
}
r = s.get('REMOVED', headers=headers)
students = json.loads(r.content.decode('utf-8'))
for n in students['d']['results']:
print(n['nameOfStudent'] + ' at ' + n['nameOfSchool'])
If you like it better, here are my two requests in cURL form.
curl -H "Host: ???" -H "Proxy-Connection: keep-alive" -H "Accept: */*" -H "Content-Type: application/json" -H "Accept-Language: en-US;q=1" -H "User-Agent: REMOVED" --data-binary '{"username":"???","language":0,"password":"???"}' --compressed <URL REMOVED>
and
curl -H "Host: REMOVED" -H "Proxy-Connection: keep-alive" -H "Accept: */*" -H "Cookie: SessID=REMOVED; SessPro=REMOVED" -H "Content-Type: application/json" -H "Accept-Language: en-US;q=1" -H "REMOVED" --compressed <URL REMOVED>
The cookie bit is handled by python requests in my python script.
I'm trying to implement this as a login (as you could probably tell) and as such I'm using the default Android Studio login activity.
It looks like this right now, but I want it to actually login and start a session.
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
return true;
}
Here's where I'm importing OkHttp3:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
}