JDK는 상태에서 약간의 지원을 제공합니다 (HTTP)는 다음과 같이 쓴 작은 예제 (구성 요소)를 설명합니다.
먼저 요청 클래스 (httprequester)를 작성하겠습니다.
이 클래스는 Java가 다음과 같이 간단한 요청을 구현하도록 코드를 캡슐화합니다.
코드 사본은 다음과 같습니다.
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;
java.util.map import;
import java.util.vector;
/**
* HTTP 요청 객체
*
* @author yymmiinngg
*/
공개 클래스 httprequester {
개인 문자열 defaultContentEncoding;
public httprequester () {
this.defaultContentEncoding = charset.defaultcharset (). name ();
}
/**
* GET 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendget (string urlstring)은 ioexception {
이 issend (urlstring, "get", null, null);
}
/**
* GET 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @param 매개 변수
* 매개 변수 세트
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendget (String urlstring, map <string, string> params)
IoException {{
return.send (urlstring, "get", params, null);
}
/**
* GET 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @param 매개 변수
* 매개 변수 세트
* @param 속성
* 요청 속성을 요청합니다
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendget (String urlstring, map <string, string> params,
map <string, string> properties)는 ioexception {
return.send (urlstring, "get", params, properties);
}
/**
* 사후 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendpost (String urlstring)는 ioexception {
return.send (urlstring, "post", null, null);
}
/**
* 사후 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @param 매개 변수
* 매개 변수 세트
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendpost (String urlstring, map <string, string> params)
IoException {{
return this.send (urlstring, "post", params, null);
}
/**
* 사후 요청을 보내십시오
*
* @param urlstring
* URL 주소
* @param 매개 변수
* 매개 변수 세트
* @param 속성
* 요청 속성을 요청합니다
* @return 응답 객체
* @throws ioexception
*/
public httprespons sendpost (String urlstring, map <string, string> params,
map <string, string> properties)는 ioexception {
issend (urlstring, "post", params, properties);
}
/**
* HTTP 요청을 보내십시오
*
* @param urlstring
* @return 반사 객체
* @throws ioexception
*/
개인 httprprons send (String urlstring, 문자열 메서드,
Map <String, String> 매개 변수, Map <String, String> Properties)
IoException {{
httpurlconnection urlconnection = null;
if (method.equalsignorecase ( "get") && parameters! = null) {
StringBuffer param = new StringBuffer ();
int i = 0;
for (문자열 키 : parameters.keyset ()) {
if (i == 0)
param.append ( "?");
또 다른
param.append ( "&");
param.append (key) .append ( "="). append (parameters.get (key));
i ++;
}
urlstring += param;
}
url url = new URL (urlstring);
urlConnection = (httpurlConnection) url.openConnection ();
urlConnection.setRequestMethod (메소드);
urlConnection.setDoOutput (true);
urlconnection.setdoinput (true);
urlConnection.setUeCaches (false);
if (propertys! = null)
for (문자열 키 : properties.keyset ()) {
urlconnection.addrequestProperty (key, properties.get (key));
}
if (method.equalsignorecase ( "post") && parameters! = null) {
StringBuffer param = new StringBuffer ();
for (문자열 키 : parameters.keyset ()) {
param.append ( "&");
param.append (key) .append ( "="). append (parameters.get (key));
}
urlConnection.getOutputStream (). 쓰기 (param.toString (). getBytes ());
urlConnection.getOutputStream (). flush ();
urlConnection.getOutputStream (). Close ();
}
this.makecontent (urlstring, urlconnection);
}
/**
* 응답 객체를 가져옵니다
*
* @param urlconnection
* @return 응답 객체
* @throws ioexception
*/
Private HttPrespons MakeContent (String Urlstring,
httpurlconnection urlconnection) ioexception {
httprpons httpresponser = new httprespons ();
노력하다 {
inputStream in = urlConnection.getInputStream ();
bufferedReader bufferedReader = new bufferedReader (
새 입력 스트리 프 리조더 (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 ();
반환 httppresponser;
} catch (ioexception e) {
e 던지기;
} 마지막으로 {
if (urlConnection! = null)
urlconnection.disconnect ();
}
}
/**
* 기본 응답 문자 세트
*/
공개 문자열 getDefaultContentEncoding () {
이 is. defaultContentEncoding;
}
/**
* 기본 응답 문자 세트를 설정하십시오
*/
public void setDefaultContentEncoding (String defaultContEntencoding) {
this.defaultContentEncoding = DefaultContentEncoding;
}
}
둘째, 응답 객체 (HTTPRPONS)를 살펴 보겠습니다. 응답 객체는 실제로 데이터 빈일 뿐이며, 다음과 같이 요청 응답의 결과 데이터를 캡슐화합니다.
코드 사본은 다음과 같습니다.
import java.util.vector;
/**
* 응답 객체
*/
공개 클래스 httprpons {
문자열 urlstring;
int defaultport;
문자열 파일;
문자열 호스트;
문자열 경로;
int 포트;
문자열 프로토콜;
문자열 쿼리;
문자열 참조;
문자열 userInfo;
문자열 내용 코딩;
문자열 내용;
문자열 contentType;
int 코드;
문자열 메시지;
문자열 방법;
int connecttimeout;
int readtimeout;
벡터 <문자열> ContentCollection;
공개 문자열 getContent () {
반환 내용;
}
공개 문자열 getContentType () {
ContentType를 반환합니다.
}
public int getCode () {
반환 코드;
}
공개 문자열 getMessage () {
반환 메시지;
}
public vector <string> getContentCollection () {
컨텐츠 수집 반환;
}
public String getContentEncoding () {
반환 콘텐츠 인코딩;
}
공개 문자열 getMethod () {
반환 방법;
}
public int getConnectTimeout () {
ConnectTimeout을 반환합니다.
}
public int getReadTimeout () {
리턴 readtimeout;
}
공개 문자열 geturlstring () {
urlstring을 반환합니다.
}
public int getDefaultport () {
반환 기본 포트;
}
공개 문자열 getFile () {
반환 파일;
}
공개 문자열 gethost () {
리턴 호스트;
}
공개 문자열 getPath () {
반환 경로;
}
public int getport () {
반환 항구;
}
공개 문자열 getProtocol () {
반환 프로토콜;
}
공개 문자열 getQuery () {
리턴 쿼리;
}
공개 문자열 getRef () {
반환 심판;
}
공개 문자열 getUserInfo () {
userinfo를 반환합니다.
}
}
마지막으로 위의 코드가 올바른지 테스트하기 위해 응용 프로그램 클래스를 작성해 봅시다.
코드 사본은 다음과 같습니다.
import com.yao.http.httprequester;
import com.yao.http.httprespons;
공개 수업 테스트 {
public static void main (String [] args) {
노력하다 {
httprequester request = new httprequester ();
httprespons hr = request.sendget ( "// www.vevb.com");
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 (예외 e) {
e.printstacktrace ();
}
}
}