doukangbin9698 2017-11-01 03:53
浏览 131
已采纳

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

I'v got a GO Lang REST API that works normally when I call it from Postman. But, when I try to call a DELETE method with HttpURLConnection parameters are not received by my method.

Request:

_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: I've got a three REST APIs in test at this moment. This method just don't pass parameters for GO Lang, using MUX. On Scala and Rails is working fine.

PS: On Go I'm getting parameter from http.Request.FormValue(field).

Go Routes:

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)

Method getting parameter:

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

Thanks for trying to help guys! Regards.

  • 写回答

1条回答 默认 最新

  • doutangguali32556 2017-11-01 08:12
    关注

    Looking at the implementation of golang's http.Request.ParseForm(), it seems that the form data is not parsed for DELETE requests.

    I'd suggest using the identifier of the city to be deleted as request parameter in the URL:

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

    While you're at it, you could also refactor the whole definition of the routes to be more consistent with standard REST API design patterns, e.g.,

    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")
    

    You can use the following snippet to inspect the request. Please note that this should only used for testing purposes and not in a production environment:

    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
    ", dump)
        var city string = r.FormValue("city")
        log.Printf("city: %q
    ", city)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用