我需要在我的 Android 应用程序的 shouldInterceptRequest 中检查请求是 POST 还是 GET。 见下面的代码:
public class CustomWebViewClient extends WebViewClient {
...
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if ("request is POST")
Log.d("CustomWebViewClient", "request is a POST");
else if ("request is GET")
Log.d("CustomWebViewClient", "request is a GET");
...
}
}
是否可以在 WebViewClient 的扩展中确定这一点?
最佳答案
可以通过扩展 WebViewClient 来实现,但它可能涉及比您预期的更多的工作。 WebViewClient 中的回调方法由 JNI 调用,您无法调用它来获取 header 和方法,因此最好的选择是使用 JavaScript。
此解决方案基于克里斯托夫对 http://code.google.com/p/android/issues/detail?id=9122#c21 的评论
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = interceptor;
window.addEventListener('submit', function(e) {
interceptor(e);
}, true);
function interceptor(e) {
var frm = e ? e.target : this;
interceptor_onsubmit(frm);
frm._submit();
}
function interceptor_onsubmit(f) {
var jsonArr = [];
for (i = 0; i < f.elements.length; i++) {
var parName = f.elements[i].name;
var parValue = f.elements[i].value;
var parType = f.elements[i].type;
jsonArr.push({
name : parName,
value : parValue,
type : parType
});
}
window.interception.customSubmit(JSON.stringify(jsonArr),
f.attributes['method'] === undefined ? null : f.attributes['method'].nodeValue,
f.attributes['enctype'] === undefined ? null : f.attributes['enctype'].nodeValue);
}
lastXmlhttpRequestPrototypeMethod = null;
XMLHttpRequest.prototype.reallyOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
lastXmlhttpRequestPrototypeMethod = method;
this.reallyOpen(method, url, async, user, password);
};
XMLHttpRequest.prototype.reallySend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
window.interception.customAjax(lastXmlhttpRequestPrototypeMethod, body);
lastXmlhttpRequestPrototypeMethod = null;
this.reallySend(body);
};
根据需要更改包/类名称。
public class JavascriptPostIntercept {
public interface JavascriptPostInterceptInterface {
public void nextMessageIsAjaxRequest(AjaxRequestContents contents);
public void nextMessageIsFormRequest(FormRequestContents contents);
}
private static String sInterceptHeader;
private JavascriptPostInterceptInterface mClient;
public static String getInterceptHeader() {
if (sInterceptHeader == null) {
// Assuming you have your own stream to string implementation
sInterceptHeader = StringUtils.readInputStream(
Resources.getSystem().openRawResource(R.raw.post_interceptor));
}
return sInterceptHeader;
}
public static class AjaxRequestContents {
private String mMethod;
private String mBody;
public AjaxRequestContents(String method, String body) {
mMethod = method;
mBody = body;
}
public String getMethod() {
return mMethod;
}
public String getBody() {
return mBody;
}
}
public static class FormRequestContents {
private String mJson;
private String mMethod;
private String mEnctype;
public FormRequestContents(String json, String method, String enctype) {
mJson = json;
mMethod = method;
mEnctype = enctype;
}
public String getJson() {
return mJson;
}
public String getMethod() {
return mMethod;
}
public String getEnctype() {
return mEnctype;
}
}
public JavascriptPostIntercept(JavascriptPostInterceptInterface client) {
mClient = client;
}
@JavascriptInterface
public void customAjax(final String method, final String body) {
mClient.nextMessageIsAjaxRequest(new AjaxRequestContents(method, body));
}
@JavascriptInterface
public void customSubmit(String json, String method, String enctype) {
mClient.nextMessageIsFormRequest(new FormRequestContents(json, method, enctype));
}
}
下面的代码只获取最新请求的 HTTP 方法,这看起来足以满足您的要求,但显然 AjaxRequestContents 和 FormSubmitContents 上的其他方法可以让您访问帖子正文和其他内容(如果您需要)
class MyWebViewClient extends WebViewClient implements JavascriptPostIntercept.JavascriptPostInterceptInterface {
private String mLastRequestMethod = "GET";
/// evaluate post_interceptor.js after the page is loaded
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript: " + JavascriptPostIntercept.getInterceptHeader());
}
@TargetApi(11)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (mLastRequestMethod.equals("POST")) {
// do stuff here...
} else if (mLastRequestMethod.equals("GET")) {
// do other stuff here...
}
// return something here...
}
@Override
public void nextMessageIsAjaxRequest(JavascriptPostIntercept.AjaxRequestContents contents) {
mLastRequestMethod = contents.getMethod();
}
@Override
public void nextMessageIsFormRequest(JavascriptPostIntercept.FormRequestContents contents) {
mLastRequestMethod = contents.getMethod();
}
}
MyWebViewClient webViewClient = new MyWebViewClient();
mWebView.setWebViewClient(webViewClient);
mWebView.addJavascriptInterface(new JavascriptPostIntercept(webViewClient), "interception");
关于Android - 检查请求是 GET 还是 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13237347/
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查
我的日期格式如下:"%d-%m-%Y"(例如,今天的日期为07-09-2015),我想看看是不是在过去的七天内。谁能推荐一种方法? 最佳答案 你可以这样做:require"date"Date.today-7 关于ruby-检查日期是否在过去7天内,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/32438063/
我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法