JAVA 는 HTTP 요청 을 보 내 고 내용 을 되 돌려 받 습 니 다.

9977 단어 JAVA
JDK 에서 무상 태 프로 토 콜 요청 (HTTP) 에 대한 지원 을 제 공 했 습 니 다. 다음은 제 가 쓴 작은 예 (구성 요소) 를 설명 하 겠 습 니 다.  우선 요청 클래스 (HttpRequester) 를 구축 합 니 다.  이 종 류 는 JAVA 가 간단 한 요청 을 실현 하 는 코드 를 봉 인 했 습 니 다. 다음 과 같 습 니 다.
package atco.http;

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 OUWCH
 */
public class HttpRequester {
	private String defaultContentEncoding;
 
	public HttpRequester() {
		this.defaultContentEncoding = Charset.defaultCharset().name();
	}
 
	/**
	 *   GET  
	 * 
	 * @param urlString
	 *            URL  
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString) throws IOException {
		return this.send(urlString, "GET", null, null);
	}
 
	/**
	 *   GET  
	 * 
	 * @param urlString
	 *            URL  
	 * @param params
	 *                
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString, Map params)
			throws IOException {
		return this.send(urlString, "GET", params, null);
	}
 
	/**
	 *   GET  
	 * 
	 * @param urlString
	 *            URL  
	 * @param params
	 *                
	 * @param propertys
	 *                
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString, Map params,
			Map propertys) throws IOException {
		return this.send(urlString, "GET", params, propertys);
	}
 
	/**
	 *   POST  
	 * 
	 * @param urlString
	 *            URL  
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString) throws IOException {
		return this.send(urlString, "POST", null, null);
	}
 
	/**
	 *   POST  
	 * 
	 * @param urlString
	 *            URL  
	 * @param params
	 *                
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString, Map params)
			throws IOException {
		return this.send(urlString, "POST", params, null);
	}
 
	/**
	 *   POST  
	 * 
	 * @param urlString
	 *            URL  
	 * @param params
	 *                
	 * @param propertys
	 *                
	 * @return     
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString, Map params,
			Map propertys) throws IOException {
		return this.send(urlString, "POST", params, propertys);
	}
 
	/**
	 *   HTTP  
	 * 
	 * @param urlString
	 * @return     
	 * @throws IOException
	 */
	private HttpRespons send(String urlString, String method,
			Map parameters, Map 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);
	}
 
	/**
	 *       
	 * 
	 * @param urlConnection
	 * @return     
	 * @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();
			StringBuffer temp = new StringBuffer();
			String line = bufferedReader.readLine();
			while (line != null) {
				httpResponser.contentCollection.add(line);
				temp.append(line).append("\r
"); 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(); } } /** * */ public String getDefaultContentEncoding() { return this.defaultContentEncoding; } /** * */ public void setDefaultContentEncoding(String defaultContentEncoding) { this.defaultContentEncoding = defaultContentEncoding; } }

그 다음 에 응답 대상 (HttpRespons) 을 살 펴 보 겠 습 니 다.
 응답 대상 은 사실 하나의 데이터 BEAN 일 뿐 입 니 다. 이 를 통 해 응답 을 요청 한 결과 데 이 터 를 밀봉 합 니 다. 다음 과 같 습 니 다. 자바 코드 
package atco.http;

import java.util.Vector;   

/**  
 * HTTP    
 * 
 * @author OUWCH
 */  
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 contentCollection;   
    
    public String getContent() {   
        return content;   
    }   
    
    public String getContentType() {   
        return contentType;   
    }   
    
    public int getCode() {   
        return code;   
    }   
    
    public String getMessage() {   
        return message;   
    }   
    
    public Vector 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;   
    }   
    
} 

마지막 으로, 우 리 는 응용 클래스 를 써 서, 상기 코드 가 정확 한 지 시험 합 시다 
package atco.http;

public class Test {

	/**
	 * @Description: TODO
	 * @param @param args    
	 * @return     
	 * @throws 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {     
            HttpRequester request = new HttpRequester();
            request.setDefaultContentEncoding("utf-8");
            HttpRespons hr = request.sendGet("http://www.csdn.net");     
      
            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();     
        } 
	}

}

좋은 웹페이지 즐겨찾기