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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么