为什么HttpURLConnection不发送HTTP请求 [英] Why does HttpURLConnection not send the HTTP request

查看:487
本文介绍了为什么HttpURLConnection不发送HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个URL并向其提交以下参数,但是如果我将BufferedReader添加到我的代码中它似乎只能工作。为什么会这样?

I would like to open an URL and submit the following parameters to it, but it only seems to work if I add the BufferedReader to my code. Why is that?

Send.php是一个脚本,它会为我的数据库添加一个带有时间的用户名。

Send.php is a script what will add an username with a time to my database.

以下代码不起作用(它不向我的数据库提交任何数据):

This following code does not work (it does not submit any data to my database):

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

但这段代码确实有效:

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

        final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        connection.disconnect();


推荐答案

据我所知。当您调用 connect()函数时,它只会创建连接。

As far as I know. When you called the connect() function, it will only create the connection.

您至少需要调用要提交的连接的 getInputStream() getResponseCode(),以便url指向的服务器能够处理请求。

You need to at least call the getInputStream() or getResponseCode() for the connection to be committed so that the server that the url is pointing to able to process the request.

这篇关于为什么HttpURLConnection不发送HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆