gpt4 book ai didi

android - 如何从 Android 发送 http post 请求?

转载 作者:行者123 更新时间:2023-11-29 14:30:28 27 4
gpt4 key购买 nike

我是 android 的新手,现在我厌倦了搜索关于 android HTTP 请求的最佳教程。

我正在尝试将这些参数发送到 phpServer,

  • Name = "某个名字"

  • email = "一些电子邮件"

我们可以在 MainActivity.java 文件中这样做吗?这需要任何 jar(库)文件吗?欢迎提出任何建议。

我试过了,

@Override
public void onClick(View view) {
if(view == btnSubscribe){
HttpURLConnection client = null;
try {
URL url = new URL("http://www/somewebsite.com/API/SUBSCRIBE");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
client.setRequestProperty("name","test one");
client.setRequestProperty("email","text@gmail.com");
client.setDoOutput(true);

OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
outputPost.flush();
outputPost.close();
client.setChunkedStreamingMode(0);

} catch(MalformedURLException error) {
showError("Handles an incorrectly entered UR");
}
catch(SocketTimeoutException error) {
showError("Handles URL access timeout");
}
catch (IOException error) {
showError("Handles input and output errors");
}finally {
if(client != null)
client.disconnect();
}
}
}

最佳答案

我正在使用此代码并且也能正常工作。试试这段代码。

public static String httpPostRequest(Context context, String url, String email) {
String response = "";
BufferedReader reader = null;
HttpURLConnection conn = null;
try {
LogUtils.d("RequestManager", url + " ");
LogUtils.e("data::", " " + data);
URL urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
+ URLEncoder.encode(email, "UTF-8");


wr.write(data);
wr.flush();

LogUtils.d("post response code", conn.getResponseCode() + " ");

int responseCode = conn.getResponseCode();



reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
LogUtils.d("Error", "error");
} finally {
try {
reader.close();
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {
}
}
LogUtils.d("RESPONSE POST", response);
return response;
}

关于android - 如何从 Android 发送 http post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38408121/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com