HTTP requests, normal get and post methods

Source: Internet
Author: User
Tags http post

A common method of get and post requests is encapsulated on a http://www.cnblogs.com/ITtangtang/p/3968093.html basis,

Although very simple, also bask

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
Import org.apache.commons.httpclient.*;
Import Org.apache.commons.httpclient.methods.PostMethod;
Import Org.apache.commons.httpclient.methods.GetMethod;

Import Java.util.Iterator;
Import Java.util.Map;
Import java.net.ConnectException;
Import java.net.SocketTimeoutException;

/**
*
* @author Zhang Jinguang
* @version $Id: Httpinvoker.java, v 0.1 October 26, 2016 PM 2:17:59 Zhang Jinguang
* EXP $
*/
public class Httpinvoker {
private static Log logger = Logfactory.getlog (Httpinvoker.class);
Default Character Set encoding
Private final static String Default_charset = "Utf-8";
Default time-out, in milliseconds (ms)
Private final static int default_timeout = 10000;

/**
* The default GET request for HTTP, the default time-out is 10s, the default character set is Utf-8, if you want to customize, call
*
* @author Zhang Jinguang October 26, 2016
* @param the URL address of the url:get request, do not take parameters, the parameters are placed inside the params
* @param params: The requested URL requires parameters, no parameters, and is passed directly to null
* @return
* @throws Exception
*/
public static string HttpGet (string url, map<?,? > params) throws Exception {
return HttpGet (URL, params, default_timeout, default_charset);
}

/**
* @author Zhang Jinguang October 26, 2016
* @param the URL address of the url:get request, do not take parameters, the parameters are placed inside the params
* @param params
* @param timeout
* @param CharSet
* @return
* @throws Exception
*/
public static string HttpGet (string url, map<?,? > params, int timeout, String charset) throws Exception {
Return invokeget (URL, params, timeout, CharSet);
}

/**
* HTTP POST request
*
* @author Zhang Jinguang October 26, 2016
* @param URL: The requested URL
* @param content of Params:post
* @return
* @throws Exception
*/
public static string HttpPost (string url, map<?,? > params) throws Exception {
Return HttpPost (URL, params, default_timeout, default_charset);
}

/**
* HTTP POST request
*
* @author Zhang Jinguang October 26, 2016
* @param URL: The requested URL
* @param content of Params:post
* @param timeout: Time Out
* @param CharSet: Character Set
* @return
* @throws Exception
*/
public static string HttpPost (string url, map<?,? > params, int timeout, String charset) throws Exception {
Return invokepost (URL, params, timeout, CharSet);
}

/**
* Actual POST request
*
* @author Zhang Jinguang October 26, 2016
* @param URL: The requested URL
* @param content of Params:post
* @param timeout: Time Out
* @param CharSet: Character Set
* @return
* @throws Exception
*/
private static string Invokepost (string url, map<?,? > params, int timeout, String charset) throws Exception {
Logger.debug ("http call post[" + URL + "[" + params + "]");
HttpMethod httpmethod = null;

if (params! = null && params.size () > 0) {
iterator<?> Paramkeys = Params.keyset (). Iterator ();
HttpMethod = new Postmethod (URL);
namevaluepair[] form = new namevaluepair[params.size ()];
int formindex = 0;
while (Paramkeys.hasnext ()) {
String key = (string) paramkeys.next ();
Object value = Params.get (key);
if (value! = null && value instanceof String &&!value.equals ("")) {
Form[formindex] = new Namevaluepair (key, (String) value);
formindex++;
} else if (value! = null && value instanceof string[] && ((string[]) value). length > 0) {
namevaluepair[] Tempform = new Namevaluepair[form.length + ((string[]) value). Length-1];
for (int i = 0; i < Formindex; i++) {
Tempform[i] = Form[i];
}
form = Tempform;
for (String V: (string[]) value) {
Form[formindex] = new Namevaluepair (key, (String) v);
formindex++;
}
}
}
((Postmethod) httpmethod). Setrequestbody (form);
}

Return executenetrequest (URL, timeout, CharSet, HttpMethod);
}

/**
* Stitching Request Parameters
*
* @author Zhang Jinguang October 26, 2016
* @param URL
* @param params
* @param timeout
* @param CharSet
* @return
* @throws Exception
*/
private static string Invokeget (string url, map<?,? > params, int timeout, String charset) throws Exception {
Logger.debug ("http call get[" + URL + "[" + params + "]");
HttpMethod httpmethod = null;

If you need to stitch request parameters
if (params! = null && params.size () > 0) {
iterator<?> Paramkeys = Params.keyset (). Iterator ();
StringBuffer getUrl = new StringBuffer (Url.trim ());
if (Url.trim (). IndexOf ("?") >-1) {
if (Url.trim (). IndexOf ("?") < Url.trim (). Length ()-1
&& Url.trim (). IndexOf ("&") < Url.trim (). Length ()-1) {
Geturl.append ("&");
}
} else {
Geturl.append ("?");
}
while (Paramkeys.hasnext ()) {
String key = (string) paramkeys.next ();
Object value = Params.get (key);
if (value! = null && value instanceof String &&!value.equals ("")) {
Geturl.append (Key). Append ("="). Append (Value). Append ("&");
} else if (value! = null && value instanceof string[] && ((string[]) value). length > 0) {
for (String V: (string[]) value) {
Geturl.append (Key). Append ("="). Append (v). Append ("&");
}
}
}
if (Geturl.lastindexof ("&") = = Geturl.length ()-1) {
HttpMethod = new GetMethod (geturl.substring (0, Geturl.length ()-1));
} else {
HttpMethod = new GetMethod (geturl.tostring ());
}
} else {//No request parameters
HttpMethod = new GetMethod (URL);
}

Return executenetrequest (URL, timeout, CharSet, HttpMethod);
}

/**
* Perform network requests
*
* @author Zhang Jinguang October 26, 2016
* @param URL
* @param timeout
* @param CharSet
* @param httpmethod
* @return
* @throws sockettimeoutexception
* @throws connectexception
* @throws Exception
*/
private static string Executenetrequest (string url, int timeout, string charset, HttpMethod HttpMethod)
Throws Sockettimeoutexception, Connectexception, Exception {
HttpClient client = new HttpClient ();
Client.getparams (). Setsotimeout (timeout);
Client.getparams (). Setcontentcharset (CharSet);

String result = "";
try {
Client.executemethod (HttpMethod);
result = Httpmethod.getresponsebodyasstring ();
} catch (Sockettimeoutexception e) {
Logger.error ("Connection timeout [" + URL + "]");
Throw e;
} catch (Java.net.ConnectException e) {
Logger.error ("Connection failed [" + URL + "]");
Throw e;
} catch (Exception e) {
Logger.error ("exception encountered when connecting [" + URL + "]");
Throw e;
} finally {
if (HttpMethod! = null) {
try {
Httpmethod.releaseconnection ();
} catch (Exception e) {
Logger.error ("Free network connection failed [" + URL + "]");
Throw e;
}
}
}

return result;
}
}

Reference post: http://www.cnblogs.com/ITtangtang/p/3968093.html

HTTP requests, normal get and post methods

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.