繁体   English   中英

Java HTTP响应代码,URL,IOException

[英]Java HTTP Response Code, URL, IOException

我正在尝试与之通信的服务器收到503响应。 现在,它在日志中向我显示了此信息,但是,我想捕获并触发了IOException,并且仅当响应代码为503且没有其他任何情况时,才进行处理。 我该怎么做?

编辑:

这是我的代码的一部分:

inURL = new BufferedReader(new InputStreamReader(myURL.openStream()));

String str;
while ((str = inURL.readLine()) != null) {
    writeTo.write(str + "\n");
}

inURL.close();

如果使用java.net.HttpURLConnection ,则使用方法getResponseCode()

如果使用org.apache.commons.httpclient.HttpClient ,则executeMethod(...)返回响应代码

这是我完成的HTTPClient:

public class HTTPClient {

    /**
     * Request the HTTP page.
     * @param uri the URI to request.
     * @return the HTTP page in a String.
     */
    public String request(String uri){

        // Create a new HTTPClient.
        HttpClient client = new HttpClient();
        // Set the parameters
        client.getParams().setParameter("http.useragent", "Test Client");
        //5000ms
        client.getParams().setParameter("http.connection.timeout",new Integer(5000));

        GetMethod method  = new GetMethod();

        try{
            method.setURI(new URI(uri, true));
            int returnCode = client.executeMethod(method);

            // The Get method failed.
            if(returnCode != HttpStatus.SC_OK){
                System.err.println("Unable to fetch default page," +
                        " status code : " + returnCode);
            }

            InputStream in = method.getResponseBodyAsStream();

            // The input isn't null.
            if (in != null) {
                StringBuilder sb = new StringBuilder();
                String line;

                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                    while ((line = reader.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                } finally {
                    in.close();
                }
                //return statement n0
                return sb.toString();
                   } 
            else {  
                //return statement n1
                return null;
            }

        } catch (HttpException he) {
            System.err.println("    HTTP failure");
        } catch (IOException ie) {
            System.err.println("    I/O problem");
        } finally {
          method.releaseConnection();
        }
        //return statement n2
        return null;        
    }
}

也许可以帮到您。

如果IOEXception catch子句属于该代码段,请处理该情况。

检查http状态代码(如果它是503)以所需的方式处理它,如果不再抛出异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM