简体   繁体   English

向服务器发送 POST 请求

[英]Sending a POST request to a server

I am trying to create my first android application that utilizes a REST api.我正在尝试创建我的第一个使用 REST api 的 android 应用程序。 My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.我的 api 是用 Node.JS 编写的,并且已经使用 Postman 进行了测试,但是,我无法将 JSON 数据发送到我的 api。

    @Override
    protected String doInBackground(String... params) {

        String data = "";
        String urlName = params[0];

        HttpURLConnection httpURLConnection = null;
        try {

            httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoOutput(true);

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(params[1]);
            wr.flush();
            wr.close();

            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in);

            int inputStreamData = inputStreamReader.read();
            while (inputStreamData != -1) {
                char current = (char) inputStreamData;
                inputStreamData = inputStreamReader.read();
                data += current;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }

        return data;
    }

I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code.我总是到达声明和初始化我的 DataOutputSteam 并且不执行代码的行。 I am not even getting a log that my Virtual device has visited my server at all.我什至没有收到我的虚拟设备访问我的服务器的日志。

I have included in the manifest XML both of these already.我已经在清单 XML 中包含了这两个。

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

Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead).根据您的日志,您遇到了NetworkOnMainThreadException并且这阻止了网络请求被执行(它会进入您的catch块)。 This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground .这表明您没有正确调用 AsyncTask - 确保您调用的是execute而不是调用doInBackground See also here for more information on this general pattern.另请参阅此处了解有关此一般模式的更多信息。

Try this, it is for POST method that accept 2 parameter email and password.试试这个,它是用于接受 2 个参数电子邮件和密码的 POST 方法。 Change it based on your requirement根据您的要求更改它

URL url = new URL(Login_url);
            HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept" , "application/json");
            conn.connect();

            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("email", "Your_Email")
                    .appendQueryParameter("password","Your_Password");
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query); 
            writer.flush();
            writer.close();
            os.close();
            code = conn.getResponseCode();

            Log.e("Result", code + "");

            InputStream input = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {

                result.append(line);

            }

            Log.e("Result",result.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM