Java HTTP tool class and httpurlconnection upload file analysis

Source: Internet
Author: User
Tags response code ssl certificate

Using HttpURLConnection in Java to upload files, we actually just know the standard format of the HTTP protocol upload file. Then you can use any language to simulate the browser to upload files. Here are a few articles from the HTTP protocol beginning to introduce the Java upload files.

  • Java uploading files using HttpURLConnection
  • Uploading files using HttpURLConnection for post requests
  • Package httpclient4.3.x including file uploads
  • File upload using HttpClient 4
  • Httpclient4 Tutorials

Below to share a package of their own HTTP tool class (not directly support file upload)------ did not introduce any three-party jar package

1 HttpRequest class

Package Com.yy.game.risecloud.sdk.common.model;import java.util.map;/** * HTTP Request class * * @author Zhuhui * */public class Ht tprequest {/** * HTTP request encoding, default UTF-8 */public String charsetname = risecloudsdkconstant.charset_name;/** * HTTP request time-out, Default 5000ms */public int timeout = risecloudsdkconstant.http_request_timeout;/*** * HTTP request URL address */public String url;/*** * HT TP Request method, only supports Get,post,put,delete */public httpmethod method;/*** * HTTP Request message header */public map<string, string> headers;/ * * HTTP request URL parameter */public map<string, string> params;/*** * HTTP request body Content */public String content;public HttpRequest () {}public httprequest (String URL, HttpMethod method) {This.url = Url;this.method = method;} Public httprequest (String URL, HttpMethod method, map<string, string> headers) {This (URL, method); this.headers = He Aders;} Public httprequest (String URL, HttpMethod method, map<string, string> headers, map<string, string> params) {T His (URL, method, headers); this.params = params;} Public HttpreQuest (String URL, HttpMethod method, map<string, string> headers, string content) {This (URL, method, headers); content = Content;}}
2. HttpResponse class
Package com.yy.game.risecloud.sdk.common.model;/** * HTTP Response class * @author Zhuhui * */public class HttpResponse {/** * HTTP response State code */public INT code;/** * HTTP Response message returned with response code */public string message;/** * Response body content */public string Content;public httpre Sponse (int code, string message, string content) {This.code = Code;this.message = Message;this.content = content;}}

3. Tool methods used (may directly copy the problem, remove the error code on it)

Package Com.yy.game.risecloud.sdk.common.internal;import Java.net.urlencoder;import Java.util.hashmap;import Java.util.list;import Java.util.map;import Java.util.map.entry;import Java.util.uuid;import com.yy.game.risecloud.sdk.common.model.risecloudsdkconstant;/** * Common Tool class * * @author Zhuhui */public class CommonUtil {PR Ivate Commonutil () {}/** * Determines if the string is empty * * @param s * @return returns True if the string is empty or the string is stripped and the trailing space is empty, and vice versa returns false */public static bool Ean IsEmpty (String s) {if (s = = NULL | | S.trim (). Length () = = 0) {return true;} return false;} /** * Determine if map is empty * * @param map * Map Object * @return if Map==null or map.size () ==0 returns True, the inverse returns false */@SuppressWarnin GS ("All") public static Boolean isEmpty (map map) {if (map = = NULL | | map.size () = = 0) {return true;} return false;} /*** * Determines whether the list is empty * * @param list * List Object * @return if List==null or list.size== returns True, the inverse returns false */@SuppressWar Nings ("All") public static Boolean isEmpty (List list) {if (list = = NULL | | list.size () = = 0) {return true;} REturn false;} /** * Convert map to HTTP URL request parameter format * * @param map * @return map NULL returns NULL, reverse returns a format similar to name=zhangsan&age=14 */public static Str ing Map2urlparams (map<string, string> map) {if (IsEmpty (map)) {return null;} StringBuilder sb = new StringBuilder (); for (entry<string, string> entry:map.entrySet ()) {if (!isempty (Entry.getva Lue ())) {string key = Entry.getkey (); try {string value = Urlencoder.encode (Entry.getvalue (), "UTF-8"); Sb.append ("&" + key + "=" + value);} catch (Exception e) {e.printstacktrace ();}}} if (sb.length () > 0) {return sb.substring (1);} return null;} public static String uuid () {return Uuid.randomuuid (). toString ();        public static string DeleteWhitespace (String str) {if (IsEmpty (str)) {return str;        } int sz = Str.length ();        char[] CHS = new CHAR[SZ];        int count = 0; for (int i = 0; i < sz; i++) {if (!        Character.iswhitespace (Str.charat (i))) {chs[count++] = Str.charat (i);    }} if (count = = SZ) {return str;    } return new String (CHS, 0, Count); }public static map<string, string> auth (String token) {map<string, string> header = new hashmap<string, Str Ing> (); Header.put (Risecloudsdkconstant.head_x_auth_token, TOKEN); return header;}}
4 HttpMethod
Package com.yy.game.risecloud.sdk.common.model;/** * HTTP Request method Enumeration class *  * @author Zhuhui *  */public enum HttpMethod { GET, POST, PUT, DELETE;}
5 Httputil class
Package Com.yy.game.risecloud.sdk.common.internal;import Java.io.bufferedreader;import Java.io.DataOutputStream; Import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;import Java.security.cert.certificateexception;import Java.security.cert.x509certificate;import Java.util.map;import Javax.net.ssl.hostnameverifier;import Javax.net.ssl.httpsurlconnection;import Javax.net.ssl.sslcontext;import Javax.net.ssl.sslsession;import Javax.net.ssl.sslsocketfactory;import Javax.net.ssl.trustmanager;import Javax.net.ssl.x509trustmanager;import Com.yy.game.risecloud.sdk.common.model.httpmethod;import com.yy.game.risecloud.sdk.common.model.HttpRequest; Import Com.yy.game.risecloud.sdk.common.model.httpresponse;public class Httputil {private Httputil () {}static Hostnameverifier sslhostnameverifier;static synchronized void Initsslhostnameverifier () {if (Sslhostnameverifier! = NULL) {return;} Sslhostnameverifier = new HosTnameverifier () {public boolean verify (String Urlhostname, sslsession session) {return urlhostname! = null && URLH Ostname.equals (Session.getpeerhost ());}};} Static sslsocketfactory sslsocketfactory;/** * Ignores SSL certificate */static synchronized void Initsslsocketfactory () {if ( Sslsocketfactory = null) {return;} InputStream in = null;try {Sslcontext context = sslcontext.getinstance ("TLS"); final X509trustmanager TrustManager = new X5 09TrustManager () {public x509certificate[] Getacceptedissuers () {return null;} public void checkclienttrusted (x509certificate[] chain, String authtype) throws certificateexception {}public void Checkservertrusted (x509certificate[] chain, String authtype) throws certificateexception {}};context.init (null, new Trustmanager[] {TrustManager}, null); sslsocketfactory = Context.getsocketfactory ();} catch (Exception e) {e.printstacktrace ();} finally {if (in! = null) {try {in.close ();} catch (IOException e) {E.printstack Trace ();}}} private static HttpURLConnection CreateConnection (String url) throws Exception {HttpURLConnection conn = (httpurlconnection) new URL (URL). OpenConnection (); if ( "https". Equalsignorecase (url.substring (0, 5)) {if (sslsocketfactory = = null) {initsslsocketfactory ();} ((httpsurlconnection) conn). Setsslsocketfactory (Sslsocketfactory); if (sslhostnameverifier = = null) { Initsslhostnameverifier ();} ((httpsurlconnection) conn). Sethostnameverifier (Sslhostnameverifier);} Conn.setusecaches (false); Conn.setinstancefollowredirects (true); Conn.setrequestproperty ("Connection", "close"); Return conn;} public static HttpResponse Execute (HttpRequest request) throws Exception {/* parameter check */if (request = = null) {throw new Illega Largumentexception ("HttpRequest must is not NULL");} if (Commonutil.isempty (Request.url)) {throw new IllegalArgumentException ("HttpRequest URL must is not NULL");} if (Request.timeout < 0) {throw new IllegalArgumentException (String.Format ("Timeout=[%s],httprequest timeout must be Greater than Zero ", Request.timeout +"));} if (requeSt.method = = Httpmethod.get &&! Commonutil.isempty (request.content)) {throw new IllegalArgumentException ("When the Http Method is get,the httprquest Content must be null ");} HttpURLConnection connection = null; String url = request.url;try {//Set URL pass parameter if (! Commonutil.isempty (Request.params)) {String queryString = Commonutil.map2urlparams (request.params); Commonutil.isempty (queryString)) {url = url + "?" + QueryString;}} Get Connection connection = createconnection (URL); Connection.setrequestmethod (request.method.toString ()); Connection.setconnecttimeout (request.timeout); Connection.setdooutput (true); Connection.setdoinput (true);// Set the request header if (! Commonutil.isempty (Request.headers)) {for (map.entry<string, string> entry:request.headers.entrySet ()) { Connection.setrequestproperty (Entry.getkey (), Entry.getvalue ());}} Connection.connect ();//Set Request body if (! Commonutil.isempty (request.content)) {DataOutputStream out = new DataOutputStream (Connection.getoutputstream ()); O Ut.write (Request.content.getBytES (Request.charsetname)); Out.close ();} int code = Connection.getresponsecode (); String message = Connection.getresponsemessage (); StringBuilder result = new StringBuilder (), InputStream in = Connection.geterrorstream (), if (in = = null) {in = CONNECTION.G Etinputstream ();} if (in! = null) {BufferedReader reader = new BufferedReader (new InputStreamReader (in)); char[] Cbuf = new Char[4096];while (true) {int len = Reader.read (CBUF); if (Len < 0) {break;} Result.append (cbuf, 0, Len);}} return new HttpResponse (code, message, result.tostring ());} catch (Exception e) {throw e;} finally {if (connection! = null) {Connection.disconnect ();}}}}

Java HTTP tool class and httpurlconnection upload file analysis

Related Article

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.