Original: pure Java implements HTTP Resource reading tool, supports sending and receiving data, does not rely on any third party jar package source code: http://www.zuidaima.com/share/1550463379950592.htm Pure Java Implementation http Resource reading tool that supports sending and receiving data without relying on any third-party jar packages
Pure Java Implements Http Resource reading tool, supports sending and receiving data, does not rely on any third party jar package
1. Fetch the resource of the specified URL, either as a stream or as a String
2. POST data to the specified URL to simulate the form submission.
For example: you want to simulate XXX automatic landing, and then post mood, signature and so on
3. Support URL Redirection
/* Copyright 2012-2013 the Haohui Network Corporation */package com.haohui.common.utils;/** * @file Httputil.java * * @brief * Httputil is a single class containing methods to conveniently perform HTTP * requests. Httputil only uses regular Java IO and net functionality and does * not depend on external libraries. * The class contains methods to perform a GET, post, put, and delete request, * and supports posting forms. Optionally, one can provide headers. * * Example Usage: * *//get * String res = httputil.get ("http://www.zuidaima.com"); * *//Post * String res = httputil.post ("http://www.zuidaima.com/share/1550463379950592.htm", "This is the data") ); * *//Post form * map<string, string> params = new hashmap<string, string> (); * Params.put ("FirstName", "Joe"); * Params.put ("LastName", "Smith"); * Params.put ("Age", "28"); * String res = httputil.postform ("Http://site.com/newuser", params); * *//append query paramEters to URL * String url = "Http://mydatabase.com/users"; * map<string, string> params = new hashmap<string, string> (); * Params.put ("by", "name"); * Params.put ("Limit", "10"); * String fullurl = httputil.appendqueryparams (URL, params); *//FullUrl = "http://mydatabase.com/user?orderby=name&limit=10" * * @license * Licensed under the Apache license , Version 2.0 (the "License"); The * use of this file except-compliance with the License. Obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by Applica BLE law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, without * WA Rranties or CONDITIONS of any KIND, either express OR implied. See the * License for the specific language governing permissions and limitations under * the License. * * Copyright (c) Almende B.V. * * @author Jos de Jong, <[email protected]> www. zuidaima.com * @date 2012-05-14 */import java.io.ioexception;import java.io.inputstream;import java.io.OutputStream; Import Java.net.httpurlconnection;import java.net.url;import Java.net.urldecoder;import Java.net.URLEncoder;import Java.util.hashmap;import java.util.map;/** * https://raw.github.com/wjosdejong/httputil/master/src/com/almende/ Util/httputil.java * * @project Baidamei * @author Cevencheng <[email protected]> * @create 2012-11-17 2:35: */public class Httputil {/** * Send a GET request * @param URL * @return Response * @throws IOException */static publi C string Get (string url) throws IOException {return get (URL, null);} /** * Send a GET request * @param URL URL As String * @param headers Optional map with headers * @return Respo NSE Response As String * @throws ioexception */static public string Get (string url,map<string, string> headers) t Hrows IOException {return fetch ("GET", URL, null, headers);} /** * Send a POST request * @param URL URL As String * @param body Request Body As String * @param headers Optional map with headers * @return Response Response As String * @throws ioexception */static public string post (string URL, string body,map<string, St ring> headers) throws IOException {return fetch ("POST", url, body, headers);} /** * Send a POST request * @param URL URL As String * @param body Request Body As String * @return Respons e Response As String * @throws ioexception */static public string post (string URL, String body) throws IOException {RET Urn post (URL, body, null);} /** * Post a form with parameters * @param URL URL As String * @param params map with parameters/values * @re Turn response Response As String * @throws ioexception */static public string postform (string url, map<string, Strin G> params) throws IOException {return postform (URL, params, null);} /** * Post a form with parameters * @param URL URL As String * @param params MAP with Parameters/values * @param headers Optional map with headers * @return Response response As String * @throws IOException */static public string postform (string url, map<string, string> params,map<string, string> Heade RS) throws IOException {//Set content typeif (headers = = null) {headers = new hashmap<string, string> ();} Headers.put ("Content-type", "application/x-www-form-urlencoded");//parse parametersstring BODY = ""; if (params! = NULL {Boolean first = True;for (String param:params.keySet ()) {if (first) {first = false;} else {body + = "&";} String value = Params.get (param), body + = Urlencoder.encode (param, "UTF-8") + "="; body + = Urlencoder.encode (value, "UTF-8" );}} Return post (URL, body, headers);} /** * Send A put request * @param URL URL As String * @param body Request Body As String * @param headers Optional map with Headers * @return Response response As String * @throws ioexception */static public string put (Str ing URL, StRing body,map<string, string> headers) throws IOException {return fetch ("PUT", url, body, headers);} /** * Send A put request * @param URL URL As String * @return response Response As String * @throws IOException */static public string put (string URL, String body) throws IOException {return put (URL, body, null);} /** * Send a delete request * @param URL URL As String * @param headers Optional map with headers * @return RE Sponse Response As String * @throws ioexception */static public string Delete (string url,map<string, string> head ERS) throws IOException {return fetch ("DELETE", URL, null, headers);} /** * Send a delete request * @param URL URL As String * @return response Response As String * @throws Ioexcepti On */static public string Delete (string url) throws IOException {return Delete (URL, null);} /** * Append query parameters to given URL * @param URL URL As String * @param params Map with query paramete RS * @return URL URL with query parameters appended * @throws ioexception */static public string appendqueryparams (string URL, map<s Tring, string> params) throws IOException {string fullurl = new String (URL); if (params! = null) {Boolean first = (fullu Rl.indexof ('? ') = =-1); for (String Param:params.keySet ()) {if (first) {FullUrl + = '? '; First = false;} else {fullurl + = ' & ';} String value = Params.get (param); FullUrl + = Urlencoder.encode (param, "UTF-8") + ' = '; FullUrl + = Urlencoder.encode (value, " UTF-8 ");}} return fullurl;} /** * Retrieve The query parameters from given URL * @param URL url containing query parameters * @return Params Map with Query parameters * @throws ioexception */static public map<string, string> getqueryparams (String URL) t Hrows IOException {map<string, string> params = new hashmap<string, string> (); int start = Url.indexof ('? '); while (Start! =-1) {//read parameter Nameint equals = url.indexof (' = ', start); String param = ""; if (equals! =-1) {param = url.substring (start + 1, equals);} else {param = url.substring (start + 1);} Read parameter valuestring value = "", if (equals! =-1) {start = Url.indexof (' & ', equals); if (start! =-1) {value = Url.substring (equals + 1, start);} else {value = url.substring (equals + 1);}} Params.put (Urldecoder.decode (param, "UTF-8"), Urldecoder.decode (value, "UTF-8"));} return params;} /** * Returns The URL without query parameters * @param URL url containing query parameters * @return URL U RL without query Parameters * @throws ioexception */static public string removequeryparams (string url) throws IOException {int q = url.indexof ('? '); if (q! =-1) {return url.substring (0, q);} else {return URL;}} /** * Send a request * @param method HTTP method, for example "GET" or "POST" * @param URL URL As String * @p Aram body Request Body As String * @param headers Optional map with headers * @return Response response as St Ring * @throws IOException */static public StRing Fetch (string method, string URL, string body,map<string, String> headers) throws IOException {//Connectionurl u = new url (URL); HttpURLConnection conn = (httpurlconnection) u.openconnection (); Conn.setconnecttimeout (10000); Conn.setReadTimeout ( 10000);//Methodif (Method! = null) {Conn.setrequestmethod (method);} Headersif (headers! = null) {for (String Key:headers.keySet ()) {Conn.addrequestproperty (key, Headers.get (key));}} Bodyif (body! = null) {Conn.setdooutput (true); OutputStream os = Conn.getoutputstream (); Os.write (Body.getbytes ()); O S.flush (); Os.close ();} Responseinputstream is = Conn.getinputstream (); String response = Streamtostring (is); Is.close ();//Handle Redirectsif (conn.getresponsecode () = = 301) {String location = C Onn.getheaderfield ("location"); return fetch (method, location, body, headers);} return response;} /** * Read An input stream to a string * @param in * @return * @throws ioexception */static public string streamtostring (InputStream in) throws IOException {StringBuffer out = new StringBuffer (); byte[] B = new byte[4096];for (int n; (n = in.read (b))! =-1;) {Out.append (new String (b, 0, N));} return out.tostring ();}}
Pure Java Implements Http Resource reading tool, supports sending and receiving data, does not rely on any third party jar package