2017-02-05 53 views
1

我想没有身体POST请求一些REST服务的URL。POST没有身体

HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); 
con.setRequestMethod("POST"); 
con.setRequestProperty("Content-Length", "0"); //tried with/without 
con.setDoOutput(true); //tried with/without 
con.connect(); 

的回应是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> 
<HTML> 
    <HEAD> 
     <TITLE>Length Required</TITLE> 
     <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"> 
    </HEAD> 
    <BODY> 
     <h2>Length Required</h2> 
     <hr> 
     <p>HTTP Error 411. The request must be chunked or have a content length.</p> 
    </BODY> 
</HTML> 

(发送POST与邮差相同的链接工作)

+2

“我尝试后没有身体要求一些REST服务URL”。为什么? – Juggernaut

+0

这是REST服务 – yuris

+0

的你尝试'setDoOutput(真)'和'的getOutputStream()相结合的要求。close()方法',实际上写的什么?你尝试'setFixedLengthStreamingMode(0)'?或者两者兼得? – Andreas

回答

0

我觉得您的网址有一些参数,这些参数在URL后添加 '?'符号。所以当你使用参数时你必须声明长度。

在这里,您可以添加参数,并得到它的长度。

String urlParameters = 
       "User=" + URLEncoder.encode("bhavik", "UTF-8") + 
         "&passwd=" + URLEncoder.encode("1234", "UTF-8")+ 

在上面的代码中设置您自己的参数和值,然后使用此行获取字符串的长度。

conn.setRequestProperty("Content-Length", ""+Integer.toString(urlParameters.getBytes().length)); 

这将为你工作,因为我有同样的问题,我解决它只是这样。