草庐IT

Java 客户端 - Go Http Mux 服务器 - go 方法参数为空

coder 2023-06-28 原文

我有一个 GO Lang REST API,当我从 Postman 调用它时,它可以正常工作。但是,当我尝试使用 HttpURLConnection 参数调用 DELETE 方法时,我的方法没有接收到参数。

要求:

_url = new URL(_urlBase+method);
_http = (HttpURLConnection) _url.openConnection();
_http.setRequestMethod(requestType);
_http.setRequestProperty("Accept", "application/json");    
if ((requestType.toUpperCase().equals("POST")) || (requestType.toUpperCase().equals("DELETE"))) 
{
    _http.setRequestProperty("Accept", "application/json"); 

    byte[] postData = params.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;

    _http.setDoOutput( true );
    _http.setInstanceFollowRedirects( false );
    _http.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    _http.setRequestProperty( "charset", "utf-8");
    _http.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    _http.setUseCaches( false );

    try( DataOutputStream wr = new DataOutputStream( _http.getOutputStream())) {
        wr.write( postData );
    }
}

if (_http.getResponseCode() != 200) {
     throw new RuntimeException("Failed : HTTP error code : " + _http.getResponseCode());
}

PS:目前我已经测试了三个 REST API。此方法只是不为 GO Lang 传递参数,使用 MUX。在 Scala 和 Rails 上运行良好。

PS:在 Go 中,我从 http.Request.FormValue(field) 获取参数。

走路线:

r := mux.NewRouter()
r.HandleFunc("/Rest/get", get).Methods("GET")
r.HandleFunc("/Rest/putCity/{city}", putCity).Methods("PUT")
r.HandleFunc("/Rest/updateCity", updateCity).Methods("POST")
r.HandleFunc("/Rest/deleteCity", deleteCity).Methods("DELETE")
http.ListenAndServe(":12345", r)

获取参数的方法:

func deleteCity(w http.ResponseWriter, r *http.Request) {   
    var city string = r.FormValue("city")
}

感谢您的帮助!问候。

最佳答案

查看 implementation在 golang 的 http.Request.ParseForm() 中,似乎没有为 DELETE 请求解析表单数据。

我建议使用要删除的城市的标识符作为 URL 中的请求参数:

r.HandleFunc("/Rest/deleteCity/{city}", deleteCity).Methods("DELETE")

同时,您还可以重构路由的整个定义,使其与标准 REST API 设计模式更加一致,例如,

r.HandleFunc("/Rest/cities/", getCities).Methods("GET")
r.HandleFunc("/Rest/cities/{city}", getCity).Methods("GET")
r.HandleFunc("/Rest/cities/{city}", createCity).Methods("POST") // with body
r.HandleFunc("/Rest/cities/{city}", updateCity).Methods("PUT") // with body
r.HandleFunc("/Rest/cities/{city}", deleteCity).Methods("DELETE")

您可以使用以下代码段来检查请求。请注意,这应该仅用于测试目的,不能用于生产环境:

func deleteCity(w http.ResponseWriter, r *http.Request) {
    log.Println("deleteCity handler called")
    dump, err := httputil.DumpRequest(r, true)
    if err != nil {
        http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
        return
    }
    log.Printf("%q\n", dump)
    var city string = r.FormValue("city")
    log.Printf("city: %q\n", city)
}

关于Java 客户端 - Go Http Mux 服务器 - go 方法参数为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047963/

有关Java 客户端 - Go Http Mux 服务器 - go 方法参数为空的更多相关文章

  1. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  2. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  7. 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/

  8. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  9. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  10. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

随机推荐