gpt4 book ai didi

java - 无法在 Java 中发送正确的 POST 请求 (Android Studio)

转载 作者:行者123 更新时间:2023-12-01 09:52:22 26 4
gpt4 key购买 nike

我正在创建一个用于提问/回答问题的应用程序。当我提问时,我遇到了 POST 请求的问题。

我尝试在终端中使用类似的东西

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "support@mlab.com"}' http://your-app-name.herokuapp.com/contacts

效果很好。

但是当我尝试在 AndroidStudio 中发送 POST 请求时,我的参数(例如姓名、姓氏、电子邮件等)不会发送。我尝试使用 https://github.com/kevinsawicki/http-request 。请求已发送(我知道,因为它显示了请求的日期),但没有任何参数。

我的代码应该更改哪些内容才能正常工作?

Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");

最佳答案

尝试这样..

Map<String, Object> params = new LinkedHashMap<>();
params.put("firstName", "Gena");
params.put("lastName", "Bukin");


JSONObject jsonObject = POST("https://safe-citadel-91138.herokuapp.com/questions", params);
/**
* Method allows to HTTP POST request to the server to send data to a specified resource
* @param serverURL URL of the API to be requested
* @param params parameter that are to be send in the "body" of the request Ex: parameter=value&amp;also=another
* returns response as a JSON object
*/
public JSONObject POST(String serverURL, Map<String, Object> params) {
JSONObject jsonObject = null;
try {
URL url = new URL(serverURL);

Log.e(TAG, params.toString());
StringBuilder postData = new StringBuilder();

for (Map.Entry<String, Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
Log.e("POST", serverURL + ":" + params.toString());
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.getOutputStream().write(postDataBytes);
connection.connect();

int statusCode = connection.getResponseCode();
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
jsonObject = new JSONObject(sb.toString());
} catch (Exception e) {
//e.printStackTrace();
}
return jsonObject;
}

关于java - 无法在 Java 中发送正确的 POST 请求 (Android Studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525153/

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