在Android中遇到POST请求问题

时间:2020-02-24 23:01:36

标签: android rest web-services post

我的宠物项目现在有一些问题。到目前为止,我一直在执行与我的Web服务相关的应用程序中的所有GET请求,没有任何问题。我最终需要发布一些数据,但是我不确定该应用程序正在发送任何内容。在WebService端,我没有在日志中看到任何内容,甚至没有失败的连接。目前,我已经尝试构建约100种方法,并验证可以通过PostMan使端点正常工作。谁能帮助我找出问题所在?我的代码将其设置为“异步完成!”日志,但似乎永远不会击中服务器。


import android.os.AsyncTask;
import android.util.Log;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class UserWebservice extends AsyncTask<Void, Void, Void> {
    private static final String TAG = UserWebservice.class.getSimpleName();
    private String username;
    private String hashedPassword;

    public UserWebservice(String username, String hashedPassword) {
        this.username = username;
        this.hashedPassword = hashedPassword;
    }

    @Override
    protected Void doInBackground(Void... params) {
        login();
        return null;
    }

    public void login() {
        String jsonString = "{\"username\":\"" + username + "\", \"hashedPassword\":\"" + hashedPassword + "\"}";

        try {
            URL url = new URL("http://ipaddress/appname/resourcename");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept","application/json");
            connection.setReadTimeout(10000);

            connection.connect();

            DataOutputStream os = new DataOutputStream(connection.getOutputStream());
            os.writeBytes(URLEncoder.encode(jsonString, "UTF-8"));

            os.flush();
            os.close();

            connection.disconnect();
            Log.d(TAG, "done with async! ");
        } catch (Exception e) {
            Log.d(TAG, "POST: exception message: " + e.getMessage());
            Log.d(TAG, "POST: exception string: " + e.toString());
            Log.d(TAG, "POST: exception: " + e.toString());
        }
    }
}

0 个答案:

没有答案