我在html文件中有一个按钮,当它被按下时,它调用www.example.com中的postData函数MainActivity.java
<script>
document.getElementById("login-button").addEventListener("click", function(event) {
event.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var role = document.getElementById("role").value;
var company = document.getElementById("company").value;
Android.postData(username, password, role, company);
});
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private String username;
private String password;
private String role;
private String company;
private Retrofit retrofit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
webView.loadUrl("file:///android_asset/index.html");
}
public class WebAppInterface {
@JavascriptInterface
public void postData(String username, String password, String role, String company) {
try {
//Test the data is fit with html input
System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println("Role: " + role);
System.out.println("Company: " + company);
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", username);
jsonObject.put("password", password);
jsonObject.put("role", role);
jsonObject.put("company", company);
String jsonString = jsonObject.toString();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
new post().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, jsonString);
} else {
new post().execute(jsonString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class post extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
try {
// on below line creating a url to post the data.
URL url = new URL("http://10.0.2.2:3000/login");
// on below line opening the connection.
HttpURLConnection client = (HttpURLConnection) url.openConnection();
// on below line setting method as post.
client.setRequestMethod("POST");
// on below line setting content type and accept type.
client.setRequestProperty("Content-Type", "application/json");
client.setRequestProperty("Accept", "application/json");
// on below line setting client.
client.setDoOutput(true);
// on below line we are creating an output stream and posting the data.
try (OutputStream os = client.getOutputStream()) {
byte[] input = strings[0].getBytes("utf-8");
os.write(input, 0, input.length);
}
// on below line creating and initializing buffer reader.
try (BufferedReader br = new BufferedReader(
new InputStreamReader(client.getInputStream(), "utf-8"))) {
// on below line creating a string builder.
StringBuilder response = new StringBuilder();
// on below line creating a variable for response line.
String responseLine = null;
// on below line writing the response
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}
} catch (Exception e) {
// on below line handling the exception.
e.printStackTrace();
}
return null;
}
}
}
提交按钮后Logcat显示:
2023-06-15 05:21:08.684 505-505 AutofillManager com.example.myapplication V requestHideFillUi(null): anchor = null
2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Username: 1
2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Password: 1
2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Role: Company
2023-06-15 05:21:08.763 505-2113 System.out com.example.myapplication I Company: Company 1
这是我的server.js:
app.post('/login', (req, res) => {
const { username, password, role, company } = req.body;
// Perform your login logic here
// For demonstration purposes, let's assume the username is "admin" and password is "password"
console.log(username, password, role, company);
if (role === 'Company' && company === 'Company 2' &&
username === 'admin2' && password === 'password') {
res.json({ success: true, message: 'org2CreateUser.html' });
}
if (role === 'Company' && company === 'Company 1' &&
username === 'admin1' && password === 'password') {
res.json({ success: true, message: 'org1CreateUser.html' });
}
if (role === 'Employer') {
credentials.forEach(element => {
if(element.username === username && element.password == password) {
res.json({ success: true, message: 'upload.html' });
return;
}
});
res.status(401).json({ success: false, message: 'Invalid username or password' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
问题是我看不到控制台。log(用户名,密码,角色,公司); respone在服务器的console.log中。当我使用curl测试服务器时,它正常显示:
curl -X POST -H "Content-Type: application/json" -d '{
"username": "admin",
"password": "password",
"role": "Company",
"company": "Company 1"
}' http://localhost:3000/login
我不知道JSON是否发送到服务器。我在ubuntu vmware中使用Android Studio,并通过usb调试连接我的手机。
1条答案
按热度按时间jljoyd4f1#
尝试检查您的Android应用程序和服务器之间的通信。
查看
AsyncTask
是否正确执行。在AndroidManifest.xml文件中检查Internet权限
如果不在localhost中,请检查您的服务器是否可以从Android设备或模拟器访问。请确保使用正确的IP地址或主机名和端口号连接到服务器。
不要使用
AsyncTask
,考虑使用HttpURLConnection
、OkHttp
或Retrofit
或Volley
等库。改装示例:
postData
中的API: