Home>
package com.snowfigure.kits.net;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstreamwriter;
import java.io.unsupportedencodingexception;
import java.net.httpurlconnection;
import java.net.inetsocketaddress;
import java.net.proxy;
import java.net.url;
import java.net.urlconnection;
import java.util.list;
import java.util.map;
/**
 * http request tool class
 * @author snowfigure
 * @since 2014-8-24 13:30:56
 * @version v1.0.1
 * /
public class httprequestutil {
  static boolean proxyset=false;
  static string proxyhost="127.0.0.1";
  static int proxyport=8087;
  /**
   * Coding
   * @param source
   * @return
   * /
  public static string urlencode (string source, string encode) {
    string result=source;
    try {
      result=java.net.urlencoder.encode (source, encode);
    } catch (unsupportedencodingexception e) {
      e.printstacktrace ();
      return "0";
    }
    return result;
  }
  public static string urlencodegbk (string source) {
    string result=source;
    try {
      result=java.net.urlencoder.encode (source, "gbk");
    } catch (unsupportedencodingexception e) {
      e.printstacktrace ();
      return "0";
    }
    return result;
  }
  /**
   * Initiate an http request to get the return result
   * @param req_url request address
   * @return
   * /
  public static string httprequest (string req_url) {
    stringbuffer buffer=new stringbuffer ();
    try {
      url url=new url (req_url);
      httpurlconnection httpurlconn=(httpurlconnection) url.openconnection ();
      httpurlconn.setdooutput (false);
      httpurlconn.setdoinput (true);
      httpurlconn.setusecaches (false);
      httpurlconn.setrequestmethod ("get");
      httpurlconn.connect ();
      //convert the returned input stream into a string
      inputstream inputstream=httpurlconn.getinputstream ();
      inputstreamreader inputstreamreader=new inputstreamreader (inputstream, "utf-8");
      bufferedreader bufferedreader=new bufferedreader (inputstreamreader);
      string str=null;
      while ((str=bufferedreader.readline ())!=null) {
        buffer.append (str);
      }
      bufferedreader.close ();
      inputstreamreader.close ();
      //release resources
      inputstream.close ();
      inputstream=null;
      httpurlconn.disconnect ();
    } catch (exception e) {
      system.out.println (e.getstacktrace ());
    }
    return buffer.tostring ();
  }
  /**
   * Send http request to get the returned input stream
   * @param requesturl request address
   * @return inputstream
   * /
  public static inputstream httprequestio (string requesturl) {
    inputstream inputstream=null;
    try {
      url url=new url (requesturl);
      httpurlconnection httpurlconn=(httpurlconnection) url.openconnection ();
      httpurlconn.setdoinput (true);
      httpurlconn.setrequestmethod ("get");
      httpurlconn.connect ();
      //get the returned input stream
      inputstream=httpurlconn.getinputstream ();
    } catch (exception e) {
      e.printstacktrace ();
    }
    return inputstream;
  }
  /**
   * Send a get method request to the specified url
   *
   * @param url
   * Send request URL
   * @param param
   * Request parameters,The request parameter should be of the form name1=value1&name2=value2.
   * The response result of the remote resource represented by @return url
   * /
  public static string sendget (string url, string param) {
    string result="";
    bufferedreader in=null;
    try {
      string urlnamestring=url + "?" + param;
      url realurl=new url (urlnamestring);
      //open the connection to the url
      urlconnection connection=realurl.openconnection ();
      //Set general request attributes
      connection.setrequestproperty ("accept", "*/*");
      connection.setrequestproperty ("connection", "keep-alive");
      connection.setrequestproperty ("user-agent",          "mozilla/4.0 (compatible;msie 6.0;windows nt 5.1;sv1)");
      //Establish the actual connection
      connection.connect ();
      //Get all response header fields
      map<string, list<string>>map=connection.getheaderfields ();
      //Iterate through all response header fields
      for (string key:map.keyset ()) {
        system.out.println (key + "--->" + map.get (key));
      }
      //Define the bufferedreader input stream to read the response of the url
      in=new bufferedreader (new inputstreamreader (
          connection.getinputstream ()));
      string line;
      while ((line=in.readline ())!=null) {
        result +=line;
      }
    } catch (exception e) {
      system.out.println ("An exception occurred while sending a get request!" + e);
      e.printstacktrace ();
    }
    //use finally block to close the input stream
    finally {
      try {
        if (in!=null) {
          in.close ();
        }
      } catch (exception e2) {
        e2.printstacktrace ();
      }
    }
    return result;
  }
  /**
   * Send a post method request to the specified URL
   *
   * @param url
   * Send request URL
   * @param param
   * Request parameters,The request parameter should be of the form name1=value1&name2=value2.
   * @param isproxy
   * Whether to use proxy mode
   * The response result of the remote resource represented by @return
   * /
  public static string sendpost (string url, string param, boolean isproxy) {
    outputstreamwriter out=null;
    bufferedreader in=null;
    string result="";
    try {
      url realurl=new url (url);
      httpurlconnection conn=null;
      if (isproxy) {//Use proxy mode
        @suppresswarnings ("static-access")
        proxy proxy=new proxy (proxy.type.direct.http, new inetsocketaddress (proxyhost, proxyport));
        conn=(httpurlconnection) realurl.openconnection (proxy);
      } else {
        conn=(httpurlconnection) realurl.openconnection ();
      }
      //open the connection to the url
      //Send a post request must be set as the following two lines
      conn.setdooutput (true);
      conn.setdoinput (true);
      conn.setrequestmethod ("post");//post method
      //Set general request attributes
      conn.setrequestproperty ("accept", "*/*");
      conn.setrequestproperty ("connection", "keep-alive");
      conn.setrequestproperty ("user-agent",          "mozilla/4.0 (compatible;msie 6.0;windows nt 5.1;sv1)");
      conn.setrequestproperty ("content-type", "application/x-www-form-urlencoded");
      conn.connect ();
      //Get the output stream corresponding to the urlconnection object
      out=new outputstreamwriter (conn.getoutputstream (), "utf-8");
      //send request parameters
      out.write (param);
      //Flush output buffer
      out.flush ();
      //Define the bufferedreader input stream to read the response of the url
      in=new bufferedreader (
          new inputstreamreader (conn.getinputstream ()));
      string line;
      while ((line=in.readline ())!=null) {
        result +=line;
      }
    } catch (exception e) {
      system.out.println ("Send an exception when sending a post request!" + e);
      e.printstacktrace ();
    }
    //Use finally block to close the output stream and input stream
    finally {
      try {
        if (out!=null) {
          out.close ();
        }
        if (in!=null) {
          in.close ();
        }
      }
      catch (ioexception ex) {
        ex.printstacktrace ();
      }
    }
    return result;
  }
  public static void main (string [] args) {
    //demo:proxy access
    string url="http://api.adf.ly/api.php";
    string para="key=youkeyid & youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
    string sr=httprequestutil.sendpost (url, para, true);
    system.out.println (sr);
  }
}
  • Previous Object type in JavaScript type system
  • Next PHP uses trim function to remove left and right strings and special characters