Created
May 5, 2012 23:00
-
-
Save Swind/2606188 to your computer and use it in GitHub Desktop.
[Scala][OAuth][JSON] Scala Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.{JSONObject, JSONArray} | |
import java.util.Date | |
/**Result** | |
{ "action_list" : [ { "action_id" : 1, | |
"action_type" : "get-all", | |
"get_deleted" : true | |
} ], | |
"client_version" : 0, | |
"latest_sync_point" : 1303995807749 | |
} | |
*/ | |
object JSONExample{ | |
def main(args: Array[String]) { | |
val rootObject = new JSONObject | |
rootObject.put("client_version",0) | |
rootObject.put("latest_sync_point",new Date().getTime) | |
val action_list = new JSONArray | |
val actionObj = new JSONObject | |
actionObj.put("action_type","get-all") | |
actionObj.put("action_id",1) | |
actionObj.put("get_deleted",true) | |
action_list.put(actionObj) | |
rootObject.put("action_list",action_list) | |
println(rootObject.toString) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val TAKSKS_URL = "https://mail.google.com/tasks/r/d" | |
def getTasksQuery(authToken:String)={ | |
//好用又邪惡的隱式轉換 | |
implicit def tuplesToNameValuePair(s:Tuple2[String,String]) = new BasicNameValuePair(s._1,s._2) | |
val actionID = 1 | |
val post = new HttpPost(TAKSKS_URL) | |
post.addHeader("AT","1") | |
post.addHeader("Cookie","GTL="+authToken) | |
val request = """ | |
{"action_list":[ | |
{ | |
"action_type":"get_all", | |
"action_id":%d, | |
"get_deleted":true | |
} | |
], | |
"client_version":0, | |
"latest_sync_point":0 | |
} | |
""" format (actionID) | |
val queryList = Arrays.asList[BasicNameValuePair]( | |
("r",request) | |
) | |
post.setEntity(new UrlEncodedFormEntity(queryList)) | |
val response = httpClient.execute(post) | |
response.getStatusLine.getStatusCode match { | |
case 200=> | |
val reader = new BufferedReader(new InputStreamReader(response.getEntity.getContent)) | |
printAll(reader) | |
case _=> | |
println(response.toString) | |
println(response.getStatusLine.getReasonPhrase) | |
println("httpRequest:"+response.getStatusLine.getStatusCode) | |
} | |
} | |
private def printAll(reader:BufferedReader):Unit={ | |
val line = reader.readLine | |
if(line != null) | |
{ | |
println(line) | |
printAll(reader) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment