草庐IT

java - POST请求变成GET

coder 2023-12-08 原文

我正在用 Java 开发 Android 和服务器应用程序。 服务器应用程序在 Jetty 上运行。 Android 应用程序是在同一台计算机上模拟的。

Android 应用程序向服务器发送 POST 请求,但服务器的处理程序将其解释为 GET。

当我使用Send HTTP Tool模拟POST请求时,它运行良好(我的意思是方法的类型是POST)。

这是 Android 应用程序的代码 fragment :

HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
        10000); // Timeout Limit
HttpResponse response;

// Create message
JSONObject json = new JSONObject();
json.put("request_type", "info");
json.put("user_name", mEmail);

// Send message and get response
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpPost post = new HttpPost("http://10.0.2.2:8080/app");
post.setEntity(se);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json; charset=UTF-8");
response = client.execute(post);

这是处理程序的代码:

public void handle(String target, Request baseRequest, 
    HttpServletRequest request, HttpServletResponse response) {
    System.out.println(request.getMethod());
}

我不知道会出现什么问题,因为我认为如果我使用 HttpPost,方法类型应该是 POST。

最佳答案

如果可以,能否请您发布完整的处理程序或处理程序初始化。但我要猜测一下答案。

我感觉您的 POST 请求实际上是通过 302 重定向的,因此处理程序正确地将其作为 GET 请求接收。

默认情况下,上下文为“/app”的 Jetty ContextHandler 实际上会将任何对“/app”的请求重定向到“/app/”,请查看 setAllowNullPathInfo .

因此您有 2 种可能的解决方案,在您的 ContextHandler 上调用 setAllowNullPathInfo(true),或者将您在客户端上的帖子 url 更改为 HttpPost post = new HttpPost("http://10.0 .2.2:8080/应用/");

它可能会帮助您在 jetty 上启用 RequestLogs,请参阅 Jetty/Tutorial/RequestLog

使用以下服务器,您可以通过请求日志看到对/app 的请求和对/app/的请求之间的区别。

public class RequestLogPost {

  public static class PostHandler extends ContextHandler {
    public PostHandler() {
      setContextPath("/app");
      // setAllowNullPathInfo(true); // enable to see difference in request handling
    }

    @Override
    public void doHandle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
      System.out.println(request.getMethod());
      response.setStatus(HttpStatus.OK_200);
      baseRequest.setHandled(true);
    }
  }

  public static void main(String[] args) throws Exception {
    Server server = new Server(5555);

    HandlerCollection handlers = new HandlerCollection();
    handlers.addHandler(new PostHandler());
    handlers.addHandler(new DefaultHandler());
    handlers.addHandler(createRequestLogHandler());

    server.setHandler(handlers);

    server.start();
    server.join();
  }

  private static RequestLogHandler createRequestLogHandler() {
    final int RETAIN_FOREVER = 0; // see RolloverFileOutputStream, 0 == forever.
    RequestLogHandler logHandler = new RequestLogHandler();

    NCSARequestLog ncsaRequestLog = new AsyncNCSARequestLog("requests.log");
    ncsaRequestLog.setAppend(true);
    ncsaRequestLog.setExtended(true);
    ncsaRequestLog.setLogTimeZone("GMT");
    ncsaRequestLog.setRetainDays(RETAIN_FOREVER);
    logHandler.setRequestLog(ncsaRequestLog);
    return logHandler;
  }
}

从请求日志中,将请求发布到“/app”,导致 302

[30/Jul/2013:12:28:09 +0000] "POST /app HTTP/1.1" 302 0

[30/Jul/2013:12:28:09 +0000] "GET /app/ HTTP/1.1" 200 0

直接请求“/app/”:

[30/Jul/2013:12:28:16 +0000] "POST /app/ HTTP/1.1" 200 0

关于java - POST请求变成GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17886865/

有关java - POST请求变成GET的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用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

  3. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读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方法

  7. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐