移动端向REST API发送变量并存储至服务器的技术求助
Hey there! I see you're stuck getting your Android app to send data to your NetBeans REST API—let's work through this step by step. Your core logic is on the right track, but there are a few common pitfalls here that we can fix:
1. 替换localhost为正确的IP地址
First off, when you use http://localhost:8080 in your Android app, it's pointing to the emulator/device's own local network, not your computer running the REST service.
- If you're using the Android Studio emulator, replace
localhostwith10.0.2.2(this is a special alias that maps to your host machine's localhost). - If you're using a physical device or a different emulator, use your computer's local network IP address (you can find this via
ipconfigon Windows orifconfigon macOS/Linux).
So your URL should look something like:
String url = "http://10.0.2.2:8080/engAppApi/webservices/engineerTable/";
2. 弃用的HttpClient类
The DefaultHttpClient and related classes you're using were deprecated in Android 6.0 (API 23). A better, more modern alternative is OkHttp—it's simpler, more reliable, and actively maintained.
First, add OkHttp to your app-level build.gradle dependencies:
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
3. 不能在主线程执行网络请求
Android strictly prohibits network operations on the main UI thread (it will throw a NetworkOnMainThreadException). You need to run your POST request in a background thread. For simplicity, let's use AsyncTask (or you can use Kotlin Coroutines/RxJava if you're using Kotlin).
4. 完善错误处理和日志
Your current code only prints exceptions, but you're not checking the HTTP response status code or reading the response body—this makes it impossible to tell if the request reached the server or what went wrong.
修正后的示例代码
Here's a revised version of your click listener using OkHttp and AsyncTask:
submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { details = editTextDetails.getText().toString(); getCurrentDateandTime(); // 替换为正确的IP地址 String url = "http://10.0.2.2:8080/engAppApi/webservices/engineerTable/"; // 构建JSON参数 JSONObject params = new JSONObject(); try { params.put("machinetype", machineType); params.put("workordernumber", workOrderNumber); params.put("employeename", employee); params.put("activity", activity); params.put("durationhours", durationHours); params.put("durationmins", durationMins); params.put("downtimehours", downTimeHours); params.put("downtimemins", downTimeMins); params.put("details", details); params.put("currentdateandtime", currentDateandTime); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed to build request data", Toast.LENGTH_SHORT).show(); return; } // 执行后台网络请求 new PostDataTask().execute(url, params.toString()); } }); // AsyncTask类处理后台网络请求 private class PostDataTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { String url = strings[0]; String jsonBody = strings[1]; OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json; charset=utf-8")); Request request = new Request.Builder() .url(url) .post(body) .build(); try { Response response = client.newCall(request).execute(); // 检查响应状态码 if (response.isSuccessful()) { return response.body().string(); } else { return "Error: " + response.code() + " - " + response.message(); } } catch (IOException e) { e.printStackTrace(); return "Network error: " + e.getMessage(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // 在主线程更新UI或显示结果 Toast.makeText(getApplicationContext(), "Request result: " + result, Toast.LENGTH_LONG).show(); Log.d("POST_REQUEST", result); } }
额外的必要配置
- 添加网络权限:在你的
AndroidManifest.xml里添加:
<uses-permission android:name="android.permission.INTERNET" />
- 处理明文HTTP(Android 9+):如果你的 REST API 用的是 HTTP(不是 HTTPS),Android 9+ blocks cleartext traffic by default. To fix this:
- Create a file
res/xml/network_security_config.xmlwith:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">10.0.2.2</domain> <!-- 替换为你的服务器IP --> </domain-config> </network-security-config> - Add this to your
AndroidManifest.xml'sapplicationtag:android:networkSecurityConfig="@xml/network_security_config"
- Create a file
调试建议
- Use Logcat to check the
POST_REQUESTlog—this will tell you exactly what the server responded with. - Double-check that your REST API is accessible from your device/emulator (try opening the API URL in the device's browser).
- Verify that all the parameter names in your JSON match exactly what your REST API expects (case-sensitive!).
You've already got the hard part done with the REST service working in Postman—these fixes should get your Android app talking to it smoothly!
内容的提问来源于stack exchange,提问作者Rajeey3

