Simple java http Proxy

Source: Internet
Author: User

To illustrate the working mechanism of the http proxy, I specifically wrote a simple proxy, removed a lot of complicated functions, and made the code as small as possible. The source code is as follows, if you are not clear about the http proxy mechanism, you can see it at a glance. [Java]/** $ RCSfile: SimpleHttpProxy. java, v $ * $ Revision: 1.1 $ * $ Date: 2013-1-9 $ ** Copyright (C) 2008 Skin, Inc. all rights reserved. ** This software is the proprietary information of Skin, Inc. * Use is subject to license terms. */package test.com. skin. http. proxy; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; Import java.net. serverSocket; import java.net. socket; import java.net. socketTimeoutException; import java.net. URL;/*** <p> Title: SimpleHttpProxy </p> * <p> Description: </p> * <p> Copyright: Copyright (c) 2006 </p> * @ author xuesong.net * @ version 1.0 */public class SimpleHttpProxy {public static final int PORT = 6666; public static final byte [] CRLF = new byte [] {0x0D, 0x0A};/*** @ param args */ Public static void main (String [] args) {ServerSocket socketServer = null; try {socketServer = new ServerSocket (PORT); while (true) {try {final Socket socket = socketServer. accept (); (new Thread () {public void run () {SimpleHttpProxy. service (socket );}}). start ();} catch (SocketTimeoutException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}} catch (Exception e) {e. pr IntStackTrace ();} finally {if (socketServer! = Null) {try {socketServer. close () ;}catch (IOException e) {}}} private static void service (Socket socket) {Socket remote = null; try {socket. setSoTimeout (2000); socket. setKeepAlive (false); InputStream inputStream = socket. getInputStream (); OutputStream outputStream = socket. getOutputStream ();/*** read the first line of the protocol header * Format: GET http://www.mytest.com HTTP/1.1 */byte [] buffer = readLine (inputStream); If (buffer. length <1) {return ;}string header = new String (buffer, "UTF-8"); String [] action = header. split (""); if (action. length <3) {return;} String address = action [1]; /*** the target address is obtained from the first line of the http protocol * the target Host should be obtained from the Host header of the Protocol. If the Host cannot be obtained, obtain from the address * here, only the host is obtained from the address to simplify the logic. Therefore, if the path is not an absolute path, ignore */if (address. startsWith ("http: //") = false) {return;} System. out. print (header); URL url = new URL (address); String Host = url. getHost (); int port = (url. getPort ()>-1? Url. getPort (): 80); remote = new Socket (host, port); InputStream remoteInputStream = remote. getInputStream (); OutputStream remoteOutputStream = remote. getOutputStream ();/*** some servers must read the protocol header at a time, for example, QQ space *. Therefore, the protocol header is read and written at a time, after writing, you must flush *. Otherwise, you will be redirected to the QQ homepage */long contentLength =-1L; ByteArrayOutputStream bos = new ByteArrayOutputStream (); bos. write (buffer, 0, buffer. length);/*** read the protocol header * or not, Write inputStream directly to remoteOutputStream * to be compatible with some servers, read the protocol header */while (buffer = readLine (inputStream )). length> 0) {header = new String (buffer, "UTF-8 "). trim (); if (header. length () <1) {break;} if (header. startsWith ("Content-Length:") {try {contentLength = Long. parseLong (header. substring (15 ). trim ();} catch (NumberFormatException e) {}} bos. write (buffer, 0, buffer. length);}/** empty line between the protocol header and the subject */Bos. write (CRLF); remoteOutputStream. write (bos. toByteArray (); remoteOutputStream. flush ();/** if contentLength */if (contentLength> 0) {copy (inputStream, remoteOutputStream, 4096, contentLength );} try {/*** write the data returned by the target host to the client * Check Content-Length, and the number of data to be written is determined based on the Content-Length * but many servers often do not return Content-Length, * No Content-Length, the read function will always read * So timeout is used to solve the blocking problem * automatically exit the thread when the timeout occurs. Otherwise, the thread cannot be released. */Remote. setSoTimeout (10000); copy (remoteInputStream, outputStream, 4096);} catch (SocketTimeoutException e) {} catch (Exception e) {e. printStackTrace () ;}} catch (Exception e) {e. printStackTrace ();} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {}try {if (remote! = Null) {remote. close () ;}} catch (IOException e) {e. printStackTrace () ;}} public static byte [] readLine (InputStream stream) throws IOException {int B =-1; ByteArrayOutputStream bos = new ByteArrayOutputStream (2048 ); while (B = stream. read ())! =-1) {if (B = '\ n') {bos. write (B); break;} bos. write (B);} return bos. toByteArray ();} public static void copy (InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException {int length = 0; byte [] buffer = new byte [bufferSize]; while (length = inputStream. read (buffer, 0, bufferSize)>-1) {outputStream. write (buffer, 0, length);} outputStream. flush ();} public static void copy (InputStream inputStream, OutputStream outputStream, int bufferSize, long size) throws IOException {if (size> 0) {int readBytes = 0; long count = size; int length = Math. min (bufferSize, (int) (size); byte [] buffer = new byte [length]; while (count> 0) {if (count> length) {readBytes = inputStream. read (buffer, 0, length);} else {readBytes = inputStream. read (buffer, 0, (int) count);} if (readBytes> 0) {outputStream. write (buffer, 0, readBytes); count-= readBytes;} else {break;} outputStream. flush ();}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.