1 HTTP
HTTP 프로토콜은 아마도 인터넷에서 가장 많이 사용되고 중요한 프로토콜 일 것입니다. 점점 더 많은 Java 응용 프로그램은 HTTP 프로토콜을 통해 네트워크 리소스에 직접 액세스해야합니다.
HTTP 프로토콜에 액세스하는 기본 기능이 JDK Java.net 패키지에 제공되었지만 JDK 라이브러리 자체는 대부분의 응용 프로그램에 충분히 풍부하고 유연하지 않습니다. HTTPClient는 HTTP 프로토콜을 지원하는 효율적이고 최신 기능이 풍부한 클라이언트 프로그래밍 툴킷을 제공하는 데 사용되며 HTTP 프로토콜의 최신 버전 및 권장 사항을 지원합니다.
일반적으로 Chrome 또는 기타 브라우저를 사용하여 웹 서버에 액세스하는데 정보를 보거나 데이터를 제출하거나 파일 업로드 등을 업로드하는 데 사용되는 웹 서버에 액세스합니다. 방문한 페이지 중 일부는 일부 일반 페이지에 불과하며 일부 사용자는 사용하기 전에 로그인해야하며 일부는 인증이 필요합니다. 일부는 HTTP와 같은 암호화를 통해 전송됩니다. 현재 이러한 상황을 처리하는 데 사용하는 브라우저에는 문제가되지 않습니다. 그러나 브라우저를 통해 서버의 리소스에 액세스 할 필요가 없다면 어떻게해야합니까? 그래서 어떻게해야합니까?
로컬 클라이언트가 작은 데모를 만들기위한 예제로 파일을 업로드하고 다운로드하도록하겠습니다. httpclient에는 두 가지 형태가 있으며, 하나는 org.apache.http 아래에 있고 다른 하나는 org.apache.commons.httpclient.httpclient입니다.
2 파일 업로드
파일 업로드는 두 가지 방식으로 구현 될 수 있으며, 하나는 이전 방법 방법이고 다른 하나는 httppost 메소드입니다. 둘이 비슷합니다. PostMethod는 FileBody를 사용하여 파일 랩핑 스트림을 감싸고 HTTPPOST는 FilePart를 사용하여 파일 흐름을 래핑합니다. 파일 스트림을 서버로 전달하면 다른 매개 변수를 동시에 전달할 수 있습니다.
2.1 클라이언트 처리
2.1.1 후 메드 방법
파일을 FilePart로 캡슐화하고 부품 배열에 넣습니다. 동시에 다른 매개 변수를 StringPart에 배치 할 수 있습니다. 여기에는 글이 없지만 매개 변수를 SetParameter 형태로 설정합니다. 여기의 httpclient는 org.apache.commons.httpclient.httpclient입니다.
public void upload (string localfile) {file file = 새 파일 (localfile); 사전 메드 파일 로스트 = 새로운 postMethod (url_str); httpclient client = new httpclient (); {// 다음 방법을 사용하여 페이지 매개 변수 제출 Filepost.setParameter ( "username", username)를 시뮬레이션 할 수 있습니다. filepost.setparameter ( "passwd", passwd); part [] part = {new FilePart (file.getName (), file)}; filepost.setRequestentity (새로운 multipartrequestity (part, filepost.getParams ())); client.gethttpconnectionManager (). getParams (). setConnectionTimeout (5000); int status = client.executemethod (FilePost); if (status == httpstatus.sc_ok) {system.out.println ( "성공적으로 업로드"); } else {System.out.println ( "업로드 실패"); }} catch (예외 예) {ex.printstacktrace (); } 마침내 {filepost.releaseConnection (); }}완료 한 후 릴리스 연결을 통해 연결을 해제해야합니다.
2.1.2 httppost 방법
이 방법은 위와 유사하지만 파일 바디가됩니다. 위의 부품 배열은 여기서 httpentity에 해당합니다. 여기의 httpclient는 org.apache.http.client.methods 아래에 있습니다.
public void upload (String localfile) {closeblehttpclient httpclient = null; CloseableHttTpresponse 응답 = null; try {httpclient = httpclients.createdefault (); // 일반 매개 변수를 업로드하고 파일을 다음 주소로 업로드하는 것은 서틀 httppost httppost = new httppost (url_str)입니다. // 파일을 스트림 객체로 변환 파일 바디 파일 BINS BIN = 새 파일 바디 (새 파일 (localFile)); StringBody username = new StringBody ( "Scott", ContentType.Create ( "Text/Plain", consts.utf_8)); StringBody Password = New StringBody ( "123456", ContentType.Create ( "Text/Plain", consts.utf_8)); httpentity reqentity = multipartentitybuilder.create () // <input type = "file"name = "file"/> .addpart ( "file", bin) // <input type = "instername"value = username> .addpart ( "username", username ", username)에 해당합니다. .짓다(); httppost.setentity (reqentity); // 요청을 시작하고 요청 응답의 응답을 반환합니다. 응답 = httpclient.execute (httppost); System.out.println ( "토큰의 응답 값 :" + response.getfirstheader ( "토큰")); // 응답 객체 가져 오기 httpentity fenentity = response.getentity (); if (inentity! = null) {// 응답 길이 system.out.println ( "응답 내용 길이 :" + 분노 .getContentLength ()); // 인쇄 응답 컨텐츠 System.out.println (EntityUtils.toString (분개, charset.forname ( "UTF-8"))); } // entityutils.consume (분개)을 파괴합니다. } catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (response! = null) {response.close (); }} catch (ioexception e) {e.printstacktrace (); } try {if (httpclient! = null) {httpclient.close (); }} catch (ioexception e) {e.printstacktrace (); }}}2.2 서버 측 처리
클라이언트의 업로드 방법에 관계없이 서버의 처리는 동일합니다. httpservletrequest를 통해 매개 변수를 얻은 후, 얻은 항목은 일반 양식 및 파일 양식으로 분류됩니다.
ServletFileUpload는 업로드 된 파일의 크기 및 인코딩 형식을 설정할 수 있습니다.
요컨대, 서버 측 처리는 얻은 매개 변수를 HTML 형태로 취급합니다.
public void processupload (httpservletrequest request, httpservletresponse 응답) {file uploadfile = 새 파일 (uploadpath); if (! uploadfile.exists ()) {uploadfile.mkdirs (); } system.out.println ( "어서, 베이비 ......"); request.setcharacterencoding ( "UTF-8"); 응답 .SetchAracterEncoding ( "UTF-8"); // 업로드 파일이 존재하는지 여부를 탐지합니다. 부울 ismultipart = servletfileupload.ismultipartContent (요청); if (ismultipart) {diskfileitemfactory factory = new diskfileitemfactory (); // 메모리에서 캐시 된 데이터 크기를 지정하고, 장치는 바이트이며, 여기에 1MB Factory.setSizetHreshold (1024*1024); // 파일 크기가 getSizetHreshold () factory.setRepository (새 파일 ( "d : // temp"))의 값을 초과 할 때 데이터 설정 데이터는 하드 디스크 디렉토리에 저장됩니다. // 새 파일 만들기 업로드 핸들러 ServletFileUpload 업로드 = 새로운 ServletFileUpload (Factory); // 단일 업로드 된 파일의 최대 크기를 지정합니다. 단위 : 바이트, 50MB UPLOAD.SETFILESIZEMAX (50 * 1024 * 1024); // 한 번에 업로드 된 다중 파일의 총 크기를 지정합니다. 단위 : 바이트, 50MB 업로드로 설정. upload.setheaderEncoding ( "UTF-8"); 목록 <fileItem> 항목 = null; 시도 {// 요청 요청 항목 = upload.parserequest (요청); } catch (fileUploadeXception e) {e.printstacktrace (); } if (items! = null) {// 양식 iterator <fileItem> iter = items.iterator (); while (iter.hasnext ()) {fileitem item = iter.next (); // 일반 양식 속성 인 경우 if (item.isformfield ()) {// 이름 속성은 입력에 해당하는 이름 속성이 <input type = "text"이름 = "content"> String name = item.getfieldName (); // 입력 문자열의 값 속성 값 = item.getString (); System.out.println ( "속성 :" + name + "속성 값 :" + value); } // 파일을 업로드하는 경우 else {// 속성 이름 String fieldName = item.getFieldName (); // 파일 업로드 경로 문자열 filename = item.getName (); filename = filename.substring (filename.lastindexof ( "/") + 1); // 업로드 된 파일의 파일 이름을 얻으십시오 {item.write (새 파일 (uploadpath, filename)); } catch (예외 e) {e.printstacktrace (); }}}}}} response.addheader ( "토큰", "hello"); }처리 후 서버는 헤더의 클라이언트에게 반환 된 간단한 정보를 설정할 수 있습니다. 리턴 클라이언트가 스트림 인 경우 스트림 크기를 미리 설정해야합니다!
response.setContentLength ((int) file.length ());
3 파일 다운로드
파일 다운로드는 httpclient의 getMethod와 Httpget 메소드 및 원래 httpurlconnection 메소드를 사용하여 구현할 수 있습니다.
3.1 클라이언트 처리
3.1.1 GetMethod 메소드
여기의 httpclient는 org.apache.commons.httpclient.httpclient입니다.
public void download (문자열 remoteFilename, 문자열 localFilename) {httpclient client = new httpclient (); getMethod get = null; fileoutputStream output = null; try {get = new getMethod (url_str); get.setRequestHeader ( "사용자 이름", 사용자 이름); get.setRequestHeader ( "passwd", passwd); get.setRequestHeader ( "filename", remoteFilename); int i = client.executemethod (get); if (success == i) {system.out.println ( "토큰의 응답 값 :" + get.getResponseHeader ( "토큰")); File StoreFile = 새 파일 (localFileName); output = 새 FileOutputStream (StoreFile); // BYTE 네트워크 리소스 배열을 가져 와서 파일 output.write (get.getResponseBody ())에 씁니다. } else {system.out.println ( "다운로드 파일 예외가 발생하고 오류 코드는 다음과 같습니다." + i); }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (output! = null) {output.close (); }} catch (ioexception e) {e.printstacktrace (); } get.releaseConnection (); client.gethttpconnectionManager (). CloseIdleConnections (0); }}3.1.2 httpget 메소드
여기의 httpclient는 org.apache.http.client.methods 아래에 있습니다.
public void download (string remoteFilename, String localFilename) {defaulthttpclient httpclient = new defaulthttpclient (); outputStream out = null; inputStream in = null; {httpget httpget = new httpget (url_str); httpget.addheader ( "사용자 이름", 사용자 이름); httpget.addheader ( "passwd", passwd); httpget.addheader ( "filename", remotefilename); httpresponse httpresponse = httpclient.execute (httpget); httpentity entity = httpresponse.getentity (); in = entity.getContent (); 긴 길이 = entity.getContentLength (); if (length <= 0) {System.out.println ( "다운로드 파일이 존재하지 않습니다!"); 반품; } system.out.println ( "토큰의 응답 값 :" + httpresponse.getfirstheader ( "토큰")); 파일 = 새 파일 (localFileName); if (! file.exists ()) {file.createnewfile (); } out = 새 FileOutputStream (파일); 바이트 [] 버퍼 = 새로운 바이트 [4096]; int readlength = 0; while ((readlength = in.read (buffer))> 0) {byte [] bytes = new Byte [readlength]; System.arrayCopy (버퍼, 0, 바이트, 0, readlength); out.write (바이트); } out.flush (); } catch (ioexception e) {e.printstacktrace (); } catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (in! = null) {in.close (); }} catch (ioexception e) {e.printstacktrace (); } try {if (out! = null) {out.close (); }} catch (ioexception e) {e.printstacktrace (); }}}3.1.3 httpurlconnection 방법
public void download3 (문자열 remoteFileName, String localFileName) {fileoutputStream out = null; inputStream in = null; {url url = new url (url_str); urlConnection urlConnection = url.openConnection (); httpurlconnection httpurlconnection = (httpurlconnection) urlconnection; // true- 매개 변수를 설정합니다 httpurlConnection.setDoOutput (true); // true- httpurlconnection.setdoinput (true)에서 읽을 수 있습니다. // 캐시를 사용하지 않습니다. // 직렬화 된 httpurlConnection.setRequestProperty 설정 ( "content-type", "application/x-java-serialized-object"); // 기본값은 httpurlConnection.setRequestMethod ( "post")를 가져옵니다. httpurlConnection.setRequestProperty ( "연결", "Keep-Alive"); httpurlconnection.setRequestProperty ( "charsert", "utf-8"); // 1 분 httpurlConnection.setConnectTimeout (60000); // 1 분 httpurlConnection.setReadTimeout (60000); httpurlconnection.addrequestProperty ( "사용자 이름", 사용자 이름); httpurlconnection.addrequestproperty ( "passwd", passwd); httpurlconnection.addrequestProperty ( "filename", ormetfilename); // 서버 (tcp)에 연결 httpurlConnection.connect (); in = httpurlConnection.getInputStream (); // 요청 보내기 // 서버 파일 = 새 파일 (localFilename); if (! file.exists ()) {file.createnewfile (); } out = 새 FileOutputStream (파일); 바이트 [] 버퍼 = 새로운 바이트 [4096]; int readlength = 0; while ((readlength = in.read (buffer))> 0) {byte [] bytes = new Byte [readlength]; System.arrayCopy (버퍼, 0, 바이트, 0, readlength); out.write (바이트); } out.flush (); } catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (in! = null) {in.close (); }} catch (ioexception e) {e.printstacktrace (); } try {if (out! = null) {out.close (); }} catch (ioexception e) {e.printstacktrace (); }}}3.2 서버 측 처리
클라이언트는 다르게 처리하지만 서버는 동일합니다.
public void processDownload (httpservletrequest 요청, httpservletresponse 응답) {int buffer_size = 4096; inputStream in = null; outputStream out = null; System.out.println ( "어서, 베이비 ......"); try {request.setcharacterencoding ( "utf-8"); 응답 .SetchAracterEncoding ( "UTF-8"); Response.setContentType ( "Application/Octet-stream"); 문자열 username = request.getheader ( "사용자 이름"); 문자열 passwd = request.getheader ( "passwd"); 문자열 filename = request.getheader ( "filename"); System.out.println ( "사용자 이름 :" + username); System.out.println ( "passwd :" + passwd); System.out.println ( "filename :" + filename); // 추가 처리는 요청이 합법적인지 확인 등 전달 된 사용자 이름 및 Passwd를 기반으로 수행 할 수 있습니다. 파일 파일 = 새 파일 (downloadpath + "//" + filename); response.setContentLength ((int) file.length ()); Response.SetHeader ( "수락-범위", "바이트"); int readlength = 0; in = new bufferedInputStream (new FileInputStream (file), buffer_size); out = new bufferedOutputStream (response.getOutputStream ()); 바이트 [] buffer = new Byte [buffer_size]; while ((readlength = in.read (buffer))> 0) {byte [] bytes = new Byte [readlength]; System.arrayCopy (버퍼, 0, 바이트, 0, readlength); out.write (바이트); } out.flush (); response.addheader ( "토큰", "hello 1"); } catch (예외 e) {e.printstacktrace (); response.addheader ( "토큰", "hello 2"); } 마침내 {if (in! = null) {try {in.close (); } catch (ioexception e) {}} if (out! = null) {try {out.close (); } catch (ioException e) {}}}}4 요약
httpclient의 가장 기본적인 기능은 HTTP 방법을 실행하는 것입니다. HTTP 방법의 실행에는 하나 이상의 HTTP 요청/HTTP 응답의 상호 작용이 포함됩니다. 일반적 으로이 프로세스는 httpclient에 의해 자동으로 처리되며 사용자에게 투명합니다. 사용자는 HTTP 요청 객체 만 제공하면되며 HTTPClient는 HTTP 요청을 대상 서버로 보내고 서버의 응답을받습니다. HTTP 요청이 성공적으로 실행되지 않으면 HTTPPClient는 예외를 던집니다. 따라서 코드를 작성할 때 마침내 처리하는 데주의를 기울이십시오.
모든 HTTP 요청에는 메소드 이름, 요청 URI 및 HTTP 버전 번호를 포함한 요청 줄이 있습니다. httpclient는 http/1.1에 정의 된 모든 HTTP 방법을 지원합니다. Get, Head, Post, Put, Delete, Trace 및 Options. 위의 업로드는 게시물을 사용하면 다운로드가됩니다.
현재 org.apache.commons.httpclient.httpclient more를 사용하십시오. 그것은 나에게 달려 있습니다 ~
위의 것은 httpclient를 사용하여 파일을 구현하는 업로드 및 다운로드 방법의 모든 내용입니다. 모두가 wulin.com을 더 지원할 수 있기를 바랍니다 ~