gpt4 book ai didi

java - 如何从 DJANGO 服务器获取和使用 HTTPResponse 消息

转载 作者:行者123 更新时间:2023-12-02 10:17:15 25 4
gpt4 key购买 nike

如何获取从 DJANGO View 返回的响应消息并将其放入 TextView 中?大多数答案都谈到使用 Httpresponse ,但正如我所读到的,它已被弃用。我使用的是 SDK v28。

Android Studio 中的 Java 代码:

private class HTTPAsyncTask_wdgt extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
try {
return HttpPost_wdgt(urls[0]);
} catch (JSONException e) {
e.printStackTrace();
return "Error!";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
}

private String HttpPost_wdgt(String myUrl) throws IOException, JSONException {

URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

JSONObject jsonObject = buildJsonObject_wdgt(); //Just takes some data from the app and returns JSON to be posted.
setPostRequestContent_wdgt(conn, jsonObject);

conn.connect();
return conn.getResponseMessage()+"";
}

private void setPostRequestContent_wdgt(HttpURLConnection conn,
JSONObject jsonObject) throws IOException {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonObject.toString());
writer.flush();
writer.close();

os.close();
}

Django View :(现在它只从发布的 JSON 返回“mac”)

@csrf_exempt
def req_exec(request):

ret = request.POST
data = json.loads(request.body)

return HttpResponse(data['mac'])

最佳答案

我通常使用 OKHttp 来获取和处理请求,这里是一个 Vogella tutorial帮助开始。

关于java - 如何从 DJANGO 服务器获取和使用 HTTPResponse 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54597099/

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