异步任务HttpPost请求DoInbackground调用web api Android Studio Java,如何添加正文字符串数组?
Posted
技术标签:
【中文标题】异步任务HttpPost请求DoInbackground调用web api Android Studio Java,如何添加正文字符串数组?【英文标题】:Async task HttpPost request DoInbackground call web api Android Studio Java, how to add body string array? 【发布时间】:2021-05-15 09:51:13 【问题描述】:我正在尝试发送原始正文请求数组,知道如何在 java android studio 中实现正文数组字符串吗?
Web API .net 框架 c# 工作:
[Route("api/login_test")]
[HttpPost]
public object login_test([FromBody] string[] Username_Password])
string UsernameOrEmail_address, Password;
UsernameOrEmail_address = Username_Password[0];
Password = Username_Password[1];
return UsernameOrEmail_address + " " + Password;
低于我想要达到的目标,这也作为参考,web api c# test on postman and workingandroid studio 的 Java Async Task:
/**
* Async task class to get json by making HTTP call
*/
private class login_test extends AsyncTask<Void, Void, Void>
HttpURLConnection conn = null ;
BufferedReader reader = null;
@Override
protected Void doInBackground(Void... voids)
try
URL url_login;
url_login = new URL(url_api + "login_test");
conn = (HttpURLConnection) url_login.openConnection();
conn.setRequestMethod("POST");
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, username);
jsonArray.put(1, password);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(String.valueOf(jsonArray));
Log.i("Body to API", String.valueOf(jsonArray));
osw.flush();
osw.close();
我在上面尝试过,但它没有成功,因为它写得不正确,而且我在失败时遇到异常
【问题讨论】:
【参考方案1】:我发现了我的问题,我必须将 Content-Type 设置为 application/json
conn.setRequestProperty("Content-Type","application/json");
【讨论】:
以上是关于异步任务HttpPost请求DoInbackground调用web api Android Studio Java,如何添加正文字符串数组?的主要内容,如果未能解决你的问题,请参考以下文章