簡體   English   中英

HttpURLConnection甚至在setDoOutput(true)之后執行get請求,setRequestMethod(“POST”)setRequestProperty(“Content”

[英]HttpURLConnection doing a get request even after setDoOutput(true), setRequestMethod(“POST”) setRequestProperty("Content

這是代碼:

String Surl = "http://mysite.com/somefile";
String charset = "UTF-8";
query = String.format("param1=%s&param2=%s",
URLEncoder.encode("param1", charset),
URLEncoder.encode("param2", charset));

HttpURLConnection urlConnection = (HttpURLConnection) new URL(Surl + "?" + query).openConnection();
urlConnection.setRequestMethod("POST");             
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("User-Agent","<em>Android</em>");
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=" + charset);                
urlConnection.connect();

以上仍然是GET請求。 我在服務器上使用PHP,並且能夠通過$_GET變量而不是$_POST變量訪問查詢的'name = value'參數
測試2.3.7(設備)。

我錯過了什么?

當您在URL中發送參數時,它們將被放入GET變量中。 您應該在請求的POST主體中發布參數以實現您要查找的內容。 您應該在connect()調用之前添加以下內容並刪除“?” +來自網址的查詢。

    urlConnection.setRequestProperty("Content-Length", String.valueOf(query.getBytes().length));            
    urlConnection.setFixedLengthStreamingMode(query.getBytes().length);

    OutputStream output = new BufferedOutputStream(urlConnection.getOutputStream());            
    output.write(query.getBytes());
    output.flush(); 
    output.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM