gpt4 book ai didi

android - 在 Android 上,在不使用 UrlEncodedFormEntity 的情况下使用 URL 编码表单数据发出 POST 请求

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:03 25 4
gpt4 key购买 nike

我有一个已经采用正确 URLEncoded 格式的字符串,我想通过 Android 上的 POST 请求将其发送到 PHP 服务器。我知道在 Android 上发送 URL 编码表单的方法使用 UrlEncodedFormEntity我知道how to use it .这样做的问题是数据进入函数时已经进行了 URL 编码并由 & 符号连接,因此使用 UrlEncodedFormEntity 将涉及大量额外工作以将其转换为 ListNameValuePairs 而我宁愿不这样做。

那么,我该如何发出正确的 POST 请求,将此字符串作为内容正文发送?

我已经尝试使用 StringEntity ,但是 PHP 服务器没有获得任何数据(空 $_POST 对象)。

我正在针对 http://test.lifewanted.com/echo.json.php 进行测试这就是

<?php echo json_encode( $_REQUEST );

这是已编码数据的示例:

partnerUserID=email%40example.com&partnerUserSecret=mypassword&command=Authenticate

最佳答案

如果您不介意使用 HttpURLConnection 而不是(推荐的)HttpClient,那么您可以这样做:

public void performPost(String encodedData) {
HttpURLConnection urlc = null;
OutputStreamWriter out = null;
DataOutputStream dataout = null;
BufferedReader in = null;
try {
URL url = new URL(URL_LOGIN_SUBMIT);
urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("POST");
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
urlc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
dataout = new DataOutputStream(urlc.getOutputStream());
// perform POST operation
dataout.writeBytes(encodedData);
int responseCode = urlc.getResponseCode();
in = new BufferedReader(new InputStreamReader(urlc.getInputStream()),8096);
String response;
// write html to System.out for debug
while ((response = in.readLine()) != null) {
System.out.println(response);
}
in.close();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

关于android - 在 Android 上,在不使用 UrlEncodedFormEntity 的情况下使用 URL 编码表单数据发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4330392/

25 4 0
文章推荐: node.js - 是否可以通过另一个 IP 向 Needle 模块发送请求?
文章推荐: objective-c - 按照他们用 NSDictionary 添加的顺序获取值
文章推荐: ios - 有没有办法仅在每个文件的基础上使用 ARC 迁移工具?
文章推荐: google-chrome - Chrome 不缓存 请求