在浏览器中工作的 URL 的 FileNotFoundException

FileNotFoundException for URL that works in browser

我正在尝试将 https://us.mc-api.net/ 中的 API 用于项目,我已将其作为测试。

public static void main(String[] args){
     try {
         URL url = new URL("http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/");
          BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
          String line;
          while ((line = in.readLine()) != null) {
                System.out.println(line);
                }
          in.close();  
                 }
                    catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("I/O Error");

                    }
                }
}

这给了我一个 IOException 错误,但是每当我在我的网络浏览器中打开同一个页面时,我得到

false,Unknown-Username

这就是我想从代码中得到的。我是新来的,真的不知道为什么会这样或为什么会这样。 编辑:StackTrace

java.io.FileNotFoundException: http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.theman1928.Test.Main.main(Main.java:13)

URL 正在返回状态代码 404,因此输入流(这里是轻微的猜测)没有被创建,因此是空的。对状态码进行排序,应该没问题。

运行 用这个 CSV 就可以了:other csv

如果错误代码对您很重要,那么您可以使用 HttpURLConnection:

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println("code:"+conn.getResponseCode());

通过这种方式,您可以在进行快速 if-then-else 检查之前处理响应代码。

这与有线协议与 java.net 类 和实际浏览器相比的工作方式有关。浏览器将比您使用的简单 java.net API 复杂得多。

如果你想在 Java 中获得等效的响应值,那么你需要使用更丰富的 HTTP API。

此代码会给您与浏览器相同的响应;但是,您需要下载 Apache HttpComponents 罐子

代码:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;

public class TestDriver
{

public static void main(String[] args)
{
    try
    {
        String url = "http://us.mc-api.net/v3/uuid/193nonaxishsl/csv";

        HttpGet httpGet = new HttpGet(url);
        getResponseFromHTTPReq(httpGet, url);
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }
}

private static String getResponseFromHTTPReq(HttpUriRequest httpReq, String url)
{
    HttpClient httpclient = HttpClients.createDefault();

    // Execute and get the response.
    HttpResponse response = null;
    HttpEntity entity = null;
    try
    {
        response = httpclient.execute(httpReq);
        entity = response.getEntity();
    }
    catch (IOException ioe)
    {
        throw new RuntimeException(ioe);
    }

    if (entity == null)
    {
        String errMsg = "No response entity back from " + url;
        throw new RuntimeException(errMsg);
    }

    String returnRes = null;
    InputStream is = null;
    BufferedReader buf = null;
    try
    {
        is = entity.getContent();
        buf = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

        StringBuilder sb = new StringBuilder();
        String s = null;
        while (true)
        {
            s = buf.readLine();
            if (s == null || s.length() == 0)
            {
                break;
            }
            sb.append(s);
        }

        returnRes = sb.toString();

        System.out.println("Response: [" + returnRes + "]");
    }
    catch (UnsupportedOperationException | IOException e)
    {
        throw new RuntimeException(e);
    }
    finally
    {
        if (buf != null)
        {
            try
            {
                buf.close();
            }
            catch (IOException e)
            {
            }
        }
        if (is != null)
        {
            try
            {
                is.close();
            }
            catch (IOException e)
            {
            }
        }
    }
    return returnRes;
}

}

输出:

Response Code : 404

Response: [false,Unknown-Username]

我用 Apache HTTP 库试过了。 API 端点似乎 return 状态代码为 404,因此您的错误。我使用的代码如下。

public static void main(String[] args) throws URISyntaxException, ClientProtocolException, IOException {
    HttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder("http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/");
    URI uri = builder.build();
    HttpGet request = new HttpGet(uri);
    HttpResponse response = httpclient.execute(request);
    System.out.println(response.getStatusLine().getStatusCode());   // 404
}

www.example.com 或任何 return 状态代码 200 关闭 http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/,这进一步证明了 API 端点的错误。你可以看看[Apache HTTP Components] library here.