android - 使用 HttpURLConnection 发出 JSON POST 请求时出错
问题描述
如何使用 HttpURLConnection 发出 JSON POST 请求,我尝试了此代码,但出现错误:
btn = (Button)findViewById(R.id.bbon);
btn.setOnClickListener(new View.OnClickListener()
{
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v)
{
try {
URL url = new URL ("https://reqres.in/api/users");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String jsonInputString = "{'name': 'Table3', 'job': 'gg12344'}";
try(OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
我将权限添加到 INTERNET 和 ACCESS_NETWORK_STATE。
解决方案
推荐阅读
- javascript - 动态点击按钮 - 访问动态内容
- python - 无法使用 python-telegram-bot 创建电报机器人菜单
- jestjs - 如何使用 jest 和酶测试 useRef 的电流?
- javascript - cy.wait 的赛普拉斯良好实践
- npm - 为什么在使用 npm install 时出现权限错误以及如何解决?
- ansible - 通过在 Jinja2/ansible 之间添加一个字符串来合并 2 个列表
- android - OPEN_APP_FEATURE 操作无法通过语音命令运行 [通过应用程序操作测试工具完美运行]
- python - Python tkinter filedialog在mac上禁用菜单
- python - Python yield 不等待阻塞调用
- spring - 如何使用 log4j appenders 写入特定文件