在Android中使用HTTP客户端以JSON格式发送POST请求的问题

syqv5f0l  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(148)

我在html文件中有一个按钮,当它被按下时,它调用www.example.com中的postData函数MainActivity.java

  1. <script>
  2. document.getElementById("login-button").addEventListener("click", function(event) {
  3. event.preventDefault();
  4. var username = document.getElementById("username").value;
  5. var password = document.getElementById("password").value;
  6. var role = document.getElementById("role").value;
  7. var company = document.getElementById("company").value;
  8. Android.postData(username, password, role, company);
  9. });

MainActivity.java:

  1. public class MainActivity extends AppCompatActivity {
  2. private String username;
  3. private String password;
  4. private String role;
  5. private String company;
  6. private Retrofit retrofit;
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. WebView webView = findViewById(R.id.webview);
  12. webView.getSettings().setJavaScriptEnabled(true);
  13. webView.addJavascriptInterface(new WebAppInterface(), "Android");
  14. webView.loadUrl("file:///android_asset/index.html");
  15. }
  16. public class WebAppInterface {
  17. @JavascriptInterface
  18. public void postData(String username, String password, String role, String company) {
  19. try {
  20. //Test the data is fit with html input
  21. System.out.println("Username: " + username);
  22. System.out.println("Password: " + password);
  23. System.out.println("Role: " + role);
  24. System.out.println("Company: " + company);
  25. JSONObject jsonObject = new JSONObject();
  26. jsonObject.put("username", username);
  27. jsonObject.put("password", password);
  28. jsonObject.put("role", role);
  29. jsonObject.put("company", company);
  30. String jsonString = jsonObject.toString();
  31. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
  32. new post().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonString);
  33. } else {
  34. new post().execute(jsonString);
  35. }
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. }
  40. }
  41. class post extends AsyncTask<String, Void, String> {
  42. @Override
  43. protected String doInBackground(String... strings) {
  44. try {
  45. // on below line creating a url to post the data.
  46. URL url = new URL("http://10.0.2.2:3000/login");
  47. // on below line opening the connection.
  48. HttpURLConnection client = (HttpURLConnection) url.openConnection();
  49. // on below line setting method as post.
  50. client.setRequestMethod("POST");
  51. // on below line setting content type and accept type.
  52. client.setRequestProperty("Content-Type", "application/json");
  53. client.setRequestProperty("Accept", "application/json");
  54. // on below line setting client.
  55. client.setDoOutput(true);
  56. // on below line we are creating an output stream and posting the data.
  57. try (OutputStream os = client.getOutputStream()) {
  58. byte[] input = strings[0].getBytes("utf-8");
  59. os.write(input, 0, input.length);
  60. }
  61. // on below line creating and initializing buffer reader.
  62. try (BufferedReader br = new BufferedReader(
  63. new InputStreamReader(client.getInputStream(), "utf-8"))) {
  64. // on below line creating a string builder.
  65. StringBuilder response = new StringBuilder();
  66. // on below line creating a variable for response line.
  67. String responseLine = null;
  68. // on below line writing the response
  69. while ((responseLine = br.readLine()) != null) {
  70. response.append(responseLine.trim());
  71. }
  72. }
  73. } catch (Exception e) {
  74. // on below line handling the exception.
  75. e.printStackTrace();
  76. }
  77. return null;
  78. }
  79. }

}
提交按钮后Logcat显示:

  1. 2023-06-15 05:21:08.684 505-505 AutofillManager com.example.myapplication V requestHideFillUi(null): anchor = null
  2. 2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Username: 1
  3. 2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Password: 1
  4. 2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Role: Company
  5. 2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Company: Company 1

这是我的server.js:

  1. app.post('/login', (req, res) => {
  2. const { username, password, role, company } = req.body;
  3. // Perform your login logic here
  4. // For demonstration purposes, let's assume the username is "admin" and password is "password"
  5. console.log(username, password, role, company);
  6. if (role === 'Company' && company === 'Company 2' &&
  7. username === 'admin2' && password === 'password') {
  8. res.json({ success: true, message: 'org2CreateUser.html' });
  9. }
  10. if (role === 'Company' && company === 'Company 1' &&
  11. username === 'admin1' && password === 'password') {
  12. res.json({ success: true, message: 'org1CreateUser.html' });
  13. }
  14. if (role === 'Employer') {
  15. credentials.forEach(element => {
  16. if(element.username === username && element.password == password) {
  17. res.json({ success: true, message: 'upload.html' });
  18. return;
  19. }
  20. });
  21. res.status(401).json({ success: false, message: 'Invalid username or password' });
  22. }
  23. });
  24. app.listen(3000, () => {
  25. console.log('Server is running on port 3000');
  26. });

问题是我看不到控制台。log(用户名,密码,角色,公司); respone在服务器的console.log中。当我使用curl测试服务器时,它正常显示:

  1. curl -X POST -H "Content-Type: application/json" -d '{
  2. "username": "admin",
  3. "password": "password",
  4. "role": "Company",
  5. "company": "Company 1"
  6. }' http://localhost:3000/login

我不知道JSON是否发送到服务器。我在ubuntu vmware中使用Android Studio,并通过usb调试连接我的手机。

jljoyd4f

jljoyd4f1#

尝试检查您的Android应用程序和服务器之间的通信。
查看AsyncTask是否正确执行。
在AndroidManifest.xml文件中检查Internet权限

  1. <uses-permission android:name="android.permission.INTERNET" />

如果不在localhost中,请检查您的服务器是否可以从Android设备或模拟器访问。请确保使用正确的IP地址或主机名和端口号连接到服务器。
不要使用AsyncTask,考虑使用HttpURLConnectionOkHttpRetrofitVolley等库。
改装示例:

  • 将依赖项添加到您的build.gradle:
  1. implementation 'com.squareup.retrofit2:retrofit:2.9.0'
  2. implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // if you're using JSON
  • 创建示例并为API定义接口:
  1. Retrofit retrofit = new Retrofit.Builder()
  2. .baseUrl("http://10.0.2.2:3000/")
  3. .addConverterFactory(GsonConverterFactory.create())
  4. .build();
  5. // API interface
  6. interface MyApi {
  7. @POST("login")
  8. Call<ResponseBody> login(@Body JsonObject body); // replace with the request body type
  9. }
  10. MyApi myApi = retrofit.create(MyApi.class);
  • 使用Retrofit调用postData中的API:
  1. public void postData(String username, String password, String role, String company) {
  2. try {
  3. JsonObject body = new JsonObject();
  4. body.addProperty("username", username);
  5. body.addProperty("password", password);
  6. body.addProperty("role", role);
  7. body.addProperty("company", company);
  8. Call<ResponseBody> call = myApi.login(body);
  9. call.enqueue(new Callback<ResponseBody>() {
  10. @Override
  11. public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
  12. if (response.isSuccessful()) {
  13. // Handle successful response
  14. // ...
  15. } else {
  16. // Handle unsuccessful response
  17. // ...
  18. }
  19. }
  20. @Override
  21. public void onFailure(Call<ResponseBody> call, Throwable t) {
  22. // Handle network failure
  23. // ...
  24. }
  25. });
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
展开查看全部

相关问题