无法发送POST

时间:2019-03-12 17:04:40

标签: android

我已经创建了自己的服务器,并且想创建一个Android应用程序,它将带有数据的请求发送给它。 我已经用邮递员测试了服务器。

我尝试使用以下答案创建POST请求:https://stackoverflow.com/a/2938787/7143020 但是很遗憾,似乎没有请求发送。

相关代码如下:

@Override
protected String doInBackground(String... strings) {
    String urlString = strings[0];
    String data = strings[1];
    OutputStream out = null;
    OutputStream outputStream;

    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        outputStream = urlConnection.getOutputStream();
        out = new BufferedOutputStream(urlConnection.getOutputStream());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(data);
        writer.close();
        out.close();

        urlConnection.connect();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

我尝试使用调试器,并且out的值为null,因此可能与

有关
out = new BufferedOutputStream(urlConnection.getOutputStream());

在AndroidManifest.xml中,我添加了两个权限:

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

如何解决此问题?

1 个答案:

答案 0 :(得分:-1)

以此替换您的doInBackground方法。它将起作用。

@Override
protected String doInBackground(String... strings) {
    String urlString = strings[0];
    String data = strings[1];
    OutputStream outputStream = null;

    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        outputStream = new BufferedOutputStream(urlConnection.getOutputStream());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.flush();
        writer.close();
        outputStream.close();

        urlConnection.connect();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

您的代码存在的问题是您已经获得了输出流并将其存储在outputStream中。因此,当您再次尝试获取它时,它将返回null。