浏览器可用的URL导致FileNotFoundException异常

3
我正在尝试在项目中使用来自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)

我本以为这会起作用,但跟踪后我发现该行应该是“false,未知用户名”。当IOException被抛出时,你能否发布堆栈跟踪信息? - Jack Andrew McKay
给定的URL返回404未找到HTTP错误,尽管它向浏览器返回内容。如果这个Web服务是你的,那么让它返回200 OK,你就没问题了。 - ManoDestra
@ManoDestra 这不是我的服务,但如果这是他们的问题,我会尝试联系他们或找到其他可用的服务。 - theman1928
@JackAndrewMcKay 发布了。 - theman1928
如果你使用http://example.com/,它能正常工作。 - ManoDestra
3个回答

5
URL返回状态码为404,因此输入流(这只是一个猜测)未被创建,因此为空。请排查状态码,然后应该就可以了。
使用此CSV运行它,它是正常的:other csv 如果错误代码对您很重要,则可以使用HttpURLConnection:
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println("code:"+conn.getResponseCode());

这样,您可以在进行快速的 if-then-else 检查之前处理响应代码。


1

这与电线协议在使用上与java.net类和实际浏览器的比较有关。浏览器比您正在使用的简单java.net API要复杂得多。

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

此代码将为您提供与浏览器相同的响应;但是,您需要下载Apache HttpComponents jars

代码:

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;
}

}

输出:

响应代码: 404

响应: [false,未知用户名]


1

我尝试使用Apache HTTP库。API端点似乎返回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
}

http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/ 替换为 www.example.com 或其他内容,返回状态码 200,这进一步证明了 API 端点存在错误。您可以在此处查看 [Apache HTTP Components] 库

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接