一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - JAVA發(fā)送HTTP請求,返回HTTP響應(yīng)內(nèi)容,應(yīng)用及實(shí)例代碼

JAVA發(fā)送HTTP請求,返回HTTP響應(yīng)內(nèi)容,應(yīng)用及實(shí)例代碼

2019-11-08 14:04java教程網(wǎng) JAVA教程

這篇文章主要介紹了JAVA發(fā)送HTTP請求,返回HTTP響應(yīng)內(nèi)容,應(yīng)用及實(shí)例代碼,需要的朋友可以參考下

JDK 中提供了一些對無狀態(tài)協(xié)議請求(HTTP )的支持,下面我就將我所寫的一個小例子(組件)進(jìn)行描述:
首先讓我們先構(gòu)建一個請求類(HttpRequester )。
該類封裝了 JAVA 實(shí)現(xiàn)簡單請求的代碼,如下:

 

復(fù)制代碼代碼如下:

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.nio.charset.Charset;  
import java.util.Map;  
import java.util.Vector;  

/** 
 * HTTP請求對象 
 *  
 * @author YYmmiinngg 
 */  
public class HttpRequester {  
    private String defaultContentEncoding;  

    public HttpRequester() {  
        this.defaultContentEncoding = Charset.defaultCharset().name();  
    }  

    /** 
     * 發(fā)送GET請求 
     *  
     * @param urlString 
     *            URL地址 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendGet(String urlString) throws IOException {  
        return this.send(urlString, "GET", null, null);  
    }  

    /** 
     * 發(fā)送GET請求 
     *  
     * @param urlString 
     *            URL地址 
     * @param params 
     *            參數(shù)集合 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendGet(String urlString, Map<String, String> params)  
            throws IOException {  
        return this.send(urlString, "GET", params, null);  
    }  

    /** 
     * 發(fā)送GET請求 
     *  
     * @param urlString 
     *            URL地址 
     * @param params 
     *            參數(shù)集合 
     * @param propertys 
     *            請求屬性 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendGet(String urlString, Map<String, String> params,  
            Map<String, String> propertys) throws IOException {  
        return this.send(urlString, "GET", params, propertys);  
    }  

    /** 
     * 發(fā)送POST請求 
     *  
     * @param urlString 
     *            URL地址 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendPost(String urlString) throws IOException {  
        return this.send(urlString, "POST", null, null);  
    }  

    /** 
     * 發(fā)送POST請求 
     *  
     * @param urlString 
     *            URL地址 
     * @param params 
     *            參數(shù)集合 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendPost(String urlString, Map<String, String> params)  
            throws IOException {  
        return this.send(urlString, "POST", params, null);  
    }  

    /** 
     * 發(fā)送POST請求 
     *  
     * @param urlString 
     *            URL地址 
     * @param params 
     *            參數(shù)集合 
     * @param propertys 
     *            請求屬性 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    public HttpRespons sendPost(String urlString, Map<String, String> params,  
            Map<String, String> propertys) throws IOException {  
        return this.send(urlString, "POST", params, propertys);  
    }  

    /** 
     * 發(fā)送HTTP請求 
     *  
     * @param urlString 
     * @return 響映對象 
     * @throws IOException 
     */  
    private HttpRespons send(String urlString, String method,  
            Map<String, String> parameters, Map<String, String> propertys)  
            throws IOException {  
        HttpURLConnection urlConnection = null;  

        if (method.equalsIgnoreCase("GET") && parameters != null) {  
            StringBuffer param = new StringBuffer();  
            int i = 0;  
            for (String key : parameters.keySet()) {  
                if (i == 0)  
                    param.append("?");  
                else  
                    param.append("&");  
                param.append(key).append("=").append(parameters.get(key));  
                i++;  
            }  
            urlString += param;  
        }  
        URL url = new URL(urlString);  
        urlConnection = (HttpURLConnection) url.openConnection();  

        urlConnection.setRequestMethod(method);  
        urlConnection.setDoOutput(true);  
        urlConnection.setDoInput(true);  
        urlConnection.setUseCaches(false);  

        if (propertys != null)  
            for (String key : propertys.keySet()) {  
                urlConnection.addRequestProperty(key, propertys.get(key));  
            }  

        if (method.equalsIgnoreCase("POST") && parameters != null) {  
            StringBuffer param = new StringBuffer();  
            for (String key : parameters.keySet()) {  
                param.append("&");  
                param.append(key).append("=").append(parameters.get(key));  
            }  
            urlConnection.getOutputStream().write(param.toString().getBytes());  
            urlConnection.getOutputStream().flush();  
            urlConnection.getOutputStream().close();  
        }  

        return this.makeContent(urlString, urlConnection);  
    }  

    /** 
     * 得到響應(yīng)對象 
     *  
     * @param urlConnection 
     * @return 響應(yīng)對象 
     * @throws IOException 
     */  
    private HttpRespons makeContent(String urlString,  
            HttpURLConnection urlConnection) throws IOException {  
        HttpRespons httpResponser = new HttpRespons();  
        try {  
            InputStream in = urlConnection.getInputStream();  
            BufferedReader bufferedReader = new BufferedReader(  
                    new InputStreamReader(in));  
            httpResponser.contentCollection = new Vector<String>();  
            StringBuffer temp = new StringBuffer();  
            String line = bufferedReader.readLine();  
            while (line != null) {  
                httpResponser.contentCollection.add(line);  
                temp.append(line).append("\r\n");  
                line = bufferedReader.readLine();  
            }  
            bufferedReader.close();  

            String ecod = urlConnection.getContentEncoding();  
            if (ecod == null)  
                ecod = this.defaultContentEncoding;  

            httpResponser.urlString = urlString;  

            httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();  
            httpResponser.file = urlConnection.getURL().getFile();  
            httpResponser.host = urlConnection.getURL().getHost();  
            httpResponser.path = urlConnection.getURL().getPath();  
            httpResponser.port = urlConnection.getURL().getPort();  
            httpResponser.protocol = urlConnection.getURL().getProtocol();  
            httpResponser.query = urlConnection.getURL().getQuery();  
            httpResponser.ref = urlConnection.getURL().getRef();  
            httpResponser.userInfo = urlConnection.getURL().getUserInfo();  

            httpResponser.content = new String(temp.toString().getBytes(), ecod);  
            httpResponser.contentEncoding = ecod;  
            httpResponser.code = urlConnection.getResponseCode();  
            httpResponser.message = urlConnection.getResponseMessage();  
            httpResponser.contentType = urlConnection.getContentType();  
            httpResponser.method = urlConnection.getRequestMethod();  
            httpResponser.connectTimeout = urlConnection.getConnectTimeout();  
            httpResponser.readTimeout = urlConnection.getReadTimeout();  

            return httpResponser;  
        } catch (IOException e) {  
            throw e;  
        } finally {  
            if (urlConnection != null)  
                urlConnection.disconnect();  
        }  
    }  

    /** 
     * 默認(rèn)的響應(yīng)字符集 
     */  
    public String getDefaultContentEncoding() {  
        return this.defaultContentEncoding;  
    }  

    /** 
     * 設(shè)置默認(rèn)的響應(yīng)字符集 
     */  
    public void setDefaultContentEncoding(String defaultContentEncoding) {  
        this.defaultContentEncoding = defaultContentEncoding;  
    }  
}  

 

其次我們來看看響應(yīng)對象(HttpRespons )。 響應(yīng)對象其實(shí)只是一個數(shù)據(jù)BEAN ,由此來封裝請求響應(yīng)的結(jié)果數(shù)據(jù),如下:

復(fù)制代碼代碼如下:

import java.util.Vector;  

/** 
 * 響應(yīng)對象 
 */  
public class HttpRespons {  

    String urlString;  

    int defaultPort;  

    String file;  

    String host;  

    String path;  

    int port;  

    String protocol;  

    String query;  

    String ref;  

    String userInfo;  

    String contentEncoding;  

    String content;  

    String contentType;  

    int code;  

    String message;  

    String method;  

    int connectTimeout;  

    int readTimeout;  

    Vector<String> contentCollection;  

    public String getContent() {  
        return content;  
    }  

    public String getContentType() {  
        return contentType;  
    }  

    public int getCode() {  
        return code;  
    }  

    public String getMessage() {  
        return message;  
    }  

    public Vector<String> getContentCollection() {  
        return contentCollection;  
    }  

    public String getContentEncoding() {  
        return contentEncoding;  
    }  

    public String getMethod() {  
        return method;  
    }  

    public int getConnectTimeout() {  
        return connectTimeout;  
    }  

    public int getReadTimeout() {  
        return readTimeout;  
    }  

    public String getUrlString() {  
        return urlString;  
    }  

    public int getDefaultPort() {  
        return defaultPort;  
    }  

    public String getFile() {  
        return file;  
    }  

    public String getHost() {  
        return host;  
    }  

    public String getPath() {  
        return path;  
    }  

    public int getPort() {  
        return port;  
    }  

    public String getProtocol() {  
        return protocol;  
    }  

    public String getQuery() {  
        return query;  
    }  

    public String getRef() {  
        return ref;  
    }  

    public String getUserInfo() {  
        return userInfo;  
    }  

}  

 

最后,讓我們寫一個應(yīng)用類,測試以上代碼是否正確

復(fù)制代碼代碼如下:

import com.yao.http.HttpRequester;  
import com.yao.http.HttpRespons;  

public class Test {  
    public static void main(String[] args) {  
        try {  
            HttpRequester request = new HttpRequester();  
            HttpRespons hr = request.sendGet("//www.ythuaji.com.cn");  

            System.out.println(hr.getUrlString());  
            System.out.println(hr.getProtocol());  
            System.out.println(hr.getHost());  
            System.out.println(hr.getPort());  
            System.out.println(hr.getContentEncoding());  
            System.out.println(hr.getMethod());  

            System.out.println(hr.getContent());  

        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  
 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 无码国产成人午夜在线观看不卡 | 狠狠色婷婷 | bt7086新片速递亚洲最新合集 | 国产精品怡红院永久免费 | 情欲满载2012美国dvd | 性欧美4khdxxxx | 2018av在线| 大乳一级一区二区三区 | 国产精品29页 | 久久久久久久电影 | 四虎影院永久网站 | 免费波多野结衣庭教师 | 性欧美hd | 欧美一区二区三区免费看 | 加勒比一本大道在线 | 国产成人精品1024在线 | 国产成人99精品免费观看 | 8天堂资源在线官网 | 妹妹骑上来蹭着蹭着就射了 | 粉嫩极品国产在线观看免费 | 嫩草影院地址一地址二 | 成人精品一区二区三区中文字幕 | 69pao强力打造免费高速 | 美女扒开屁股让我桶免费 | 精品在线免费播放 | 女子监狱第二季在线观看免费完整版 | 暗卫调教女主肉高h | 天天舔天天干天天操 | 亚洲29p | 久久精品热在线观看30 | 国产v在线播放 | 日本一区视频 | 果冻传媒在线视频播放观看 | 日本加勒比在线播放 | 极品虎白女在线观看一线天 | 国产在线观看网站 | 91免费永久国产在线观看 | 午夜影院费试看黄 | 好紧好爽的午夜寂寞视频 | 亚洲成年网站在线777 | 亚洲精品有码在线观看 |