我正在写一个函数:
1)发送HTTP GET请求(响应是有效的JSON)
2)解析对json对象的响应
代码段:
val page = url("http://graph.facebook.com/9098498615")
val response = Http(page OK dispatch.as.String)
Await.result(response , 10 seconds)
val myJson= JSON.parseFull(response .toString)
//this isnt helping -> val myJson= JSON.parseRaw(response .toString)
问题是在此myJson为None之后,我希望它保存响应中的json数据。
帮助 ?
使用此方法不是一个好主意,Http(page OK as.String)
因为与HTTP 200不同的所有响应都将导致Future失败。如果您需要对错误处理/报告进行更细粒度的控制,请针对特定方案。
import org.jboss.netty.handler.codec.http.{ HttpRequest, HttpResponse, HttpResponseStatus }
def getFacebookGraphData: Either[Exception, String] = {
val page = url("http://graph.facebook.com/9098498615")
val request = Http(page.GET);
val response = Await.result(request, 10 seconds);
(response.getStatusCode: @annotation.switch) match {
case HttpResponseStatus.OK => {
val body = response.getResponseBody() // dispatch adds this method
// if it's not available, then:
val body = new String(response.getContent.array);
Right(body)
}
// If something went wrong, you now have an exception with a message.
case _ => Left(new Exception(new String(response.getContent.array)));
}
}
默认的Scala JSON库也不是一个好主意,与其他库相比,它非常粗糙。尝试lift-json
例如。
import net.liftweb.json.{ JSONParser, MappingException, ParseException };
case class FacebookGraphResponse(name: String, id: String);// etc
implicit val formats = net.liftweb.DefaultFormats;
val graphResponse = JSONParser.parse(body).extract[FacebookGraphResponse];
// or the better thing, you can catch Mapping and ParseExceptions.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句