标签‘get’

用Java发起HTTP请求与获取状态码(含状态码列表)

在使用Java请求Web程序比如访问WebService接口时,通常需要先判断访问URL的有效性,这里就Java发送HTTP请求的方式做简单记录,按照前辈们的说法,Java发HTTP请求,最常见的无非是两种,一种是用java.net.URLConnection,另一种则是大名鼎鼎的HttpClient。使用java.net.URLConnection比较麻烦,而HttpClient则比较简便。以发送POST请求为例

java.net.URLConnection方法如下:

private static void urlConnectionPost() {
    StringBuilder responseBuilder = null;
    BufferedReader reader = null;
    OutputStreamWriter wr = null;
    URL url;
    try {
        url = new URL("http://www.poorren.com");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(1000 * 5);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write("");
        wr.flush();
        // Get the response
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        responseBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            responseBuilder.append(line + "\n");
        }
        wr.close();
        reader.close();
        System.out.println(responseBuilder.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

查看更多...

无觅相关文章插件,快速提升流量