ttpURLConnection类做一个GET请求即使setDo

ttpURLConnection类做一个GET请求即使setDo

本文介绍了HttpURLConnection类做一个GET请求即使setDoOutput(真),setRequestMethod(QUOT; POST")调用setRequestProperty(QUOT;内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是code:

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 变量来访问查询的名称=值PARAMS,而不是 $ _ POST 变量结果
经测试2.3.7(设备)上。

The above still does a GET request. I am using PHP on the server and am able to access the query's 'name=value' params through the $_GET variable and not the $_POST variable
Tested on 2.3.7(device).

我是什么失踪?

推荐答案

当你在它们被放在GET变量的URL发送参数。你应该张贴请求的POST主体的参数,以达到你所期待的。您应该添加以下只是connect()调用之前去掉? +的URL查询。

When you send parameters in the url they are put in the GET variable. You should be posting the parameters in the POST body of the request to achieve what you are looking for. You should add the following just before the connect() call and remove the "?" + query from the url.

    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();

这篇关于HttpURLConnection类做一个GET请求即使setDoOutput(真),setRequestMethod(QUOT; POST&QUOT;)调用setRequestProperty(QUOT;内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:11