HttpURLConnection:结果json-code建议页面不存在(404),即使url正确

时间:2016-09-15 15:20:30

标签: java php mysql http-status-code-404

我正在尝试使用php文件从MySQL数据库中获取数据。我的java代码如下:

    HttpURLConnection conn = null;
    URL url = null;

    try {

        url = new URL(getURL);
        System.out.println(getURL);
        conn = (HttpURLConnection)url.openConnection();

        //conn.setReadTimeout(READ_TIMEOUT);
        //conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestMethod("POST");

        // setDoInput and setDoOutput method depict handling of both send and receive
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Append parameters to URL
        Uri.Builder builder = new Uri.Builder();
        builder.appendQueryParameter("user", USER);
        builder.appendQueryParameter("pass", PASS);
        builder.appendQueryParameter("server", SERVER);
        builder.appendQueryParameter("db", DB);

        String query = builder.build().getEncodedQuery();

        // Open connection for sending data
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
        conn.connect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    try {
        int response_code = conn.getResponseCode();

        // Check if successful connection made
        if (response_code == HttpURLConnection.HTTP_OK) {

            // Read data sent from server
            InputStream input = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            result = reader.readLine();
            return(result);

        }else{
            return("unsuccessful");
        }

当我使用浏览器访问我的网址(隐藏在变量getURL中)时,我会在屏幕上看到json字符串,就像它应该的那样。但是,当我输出阅读器的内容时​​(上面的代码只占第一行,但通过调整我可以的代码,当然,输出更多)它显示了显示404的网站的html代码 - 页面不存在消息。

任何人都知道出了什么问题?是的,我确实检查过拼写错误。

1 个答案:

答案 0 :(得分:0)

好的,我不知道发生了什么,因为我没有改变任何事情。但突然间它开始起作用了吗?!?

一定是服务器端的东西,我想......

感谢您的投入和分享您的想法!