HTTP tool classes for Java

Source: Internet
Author: User
Tags log log

Import java.io.IOException;

Import java.io.UnsupportedEncodingException;
Import Java.net.URLEncoder;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import Java.util.Set;

Import org.apache.commons.httpclient.HttpClient;
Import org.apache.commons.httpclient.HttpException;
Import Org.apache.commons.httpclient.HttpStatus;
Import Org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
Import Org.apache.commons.httpclient.methods.GetMethod;
Import Org.apache.commons.httpclient.methods.PostMethod;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;

Import Flexjson. JSON;

/**
* HTTP Tool class
*
* @author Yaonian
*
*/
public class Httputils {

private static log log = Logfactory.getlog (Httputils.class);

/**
* Define the encoding format UTF-8
*/
public static final String Url_param_decodecharset_utf8 = "UTF-8";

/**
* Define the encoding format GBK
*/
public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";

private static final String Url_param_connect_flag = "&";

private static final String EMPTY = "";

private static Multithreadedhttpconnectionmanager ConnectionManager = null;

private static int connectiontimeout = 25000;

private static int sockettimeout = 25000;

private static int maxconnectionperhost = 20;

private static int maxtotalconnections = 20;

private static HttpClient client;

static{
ConnectionManager = new Multithreadedhttpconnectionmanager ();
Connectionmanager.getparams (). Setconnectiontimeout (ConnectionTimeout);
Connectionmanager.getparams (). Setsotimeout (Sockettimeout);
Connectionmanager.getparams (). Setdefaultmaxconnectionsperhost (Maxconnectionperhost);
Connectionmanager.getparams (). Setmaxtotalconnections (maxtotalconnections);
Client = new HttpClient (ConnectionManager);
}

/**
* Post mode submit data
* @param URL
* URL to be requested
* @param params
* The data to be submitted
* @param ENC
* Code
* @return
* Response Results
* @throws IOException
* IO exception
*/
public static string Urlpost (string url, map<string, string> params, string enc) {

String response = EMPTY;
Postmethod postmethod = null;
try {
Postmethod = new Postmethod (URL);
Postmethod.setrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=" + enc);
Put the value of the form into Postmethod
set<string> KeySet = Params.keyset ();
for (String Key:keyset) {
String value = Params.get (key);
Postmethod.addparameter (key, value);
}
Executive Postmethod
int statusCode = Client.executemethod (Postmethod);
if (StatusCode = = HTTPSTATUS.SC_OK) {
Response = postmethod.getresponsebodyasstring ();
}else{
Log.error ("Response Status code =" + Postmethod.getstatuscode ());
}
}catch (HttpException e) {
Log.error ("A fatal exception could be a problem with the protocol or the returned content", E);
E.printstacktrace ();
}catch (IOException e) {
Log.error ("Network exception occurred", E);
E.printstacktrace ();
}finally{
if (Postmethod! = null) {
Postmethod.releaseconnection ();
Postmethod = null;
}
}

return response;
}

/**
* Get method to submit data
* @param URL
* URL to be requested
* @param params
* The data to be submitted
* @param ENC
* Code
* @return
* Response Results
* @throws IOException
* IO exception
*/
public static string Urlget (string url, map<string, string> params, string enc) {

String response = EMPTY;
GetMethod GetMethod = null;
StringBuffer Strttotalurl = new StringBuffer (EMPTY);

if (Strttotalurl.indexof ("?") = =-1) {
Strttotalurl.append (URL). Append ("?"). Append (GetUrl (params, enc));
} else {
Strttotalurl.append (URL). Append ("&"). Append (GetUrl (params, enc));
}
Log.debug ("Get request URL = \ n" + strttotalurl.tostring ());

try {
GetMethod = new GetMethod (strttotalurl.tostring ());
Getmethod.setrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=" + enc);
Executive GetMethod
int statusCode = Client.executemethod (GetMethod);
if (StatusCode = = HTTPSTATUS.SC_OK) {
Response = getmethod.getresponsebodyasstring ();
}else{
Log.debug ("Response Status code =" + Getmethod.getstatuscode ());
}
}catch (HttpException e) {
Log.error ("A fatal exception could be a problem with the protocol or the returned content", E);
E.printstacktrace ();
}catch (IOException e) {
Log.error ("Network exception occurred", E);
E.printstacktrace ();
}finally{
if (GetMethod! = null) {
Getmethod.releaseconnection ();
GetMethod = null;
}
}

return response;
}

/**
* Generate URL string according to map
* @param map
* MAP
* @param valueenc
* URL encoding
* @return
* URL
*/
private static String GetUrl (map<string, string> Map, String valueenc) {

if (null = = Map | | map.keyset (). Size () = = 0) {
return (EMPTY);
}
StringBuffer url = new StringBuffer ();
set<string> keys = Map.keyset ();
for (iterator<string> it = Keys.iterator (); It.hasnext ();) {
String key = It.next ();
if (Map.containskey (key)) {
String val = map.get (key);
String str = val! = null? Val:empty;
try {
str = Urlencoder.encode (str, VALUEENC);
} catch (Unsupportedencodingexception e) {
E.printstacktrace ();
}
Url.append (Key). Append ("="). Append (str). append (Url_param_connect_flag);
}
}
String strURL = EMPTY;
strURL = Url.tostring ();
if (url_param_connect_flag.equals (EMPTY + Strurl.charat (strurl.length ()-1))) {
strURL = strurl.substring (0, Strurl.length ()-1);
}

return (strURL);
}


public static void Main (string[] args) {

String url = "http://192.168.1.7:9909/";//project path
String charset = "Utf-8"; Encoding format
String httporgcreatetest = URL + "Send"; Full path
map<string,string> Createmap = new hashmap<string,string> (); Parameter key-value pairs

Such as
Createmap.put ("Shebeihao", "01111");
Createmap.put ("StartTime", "2017-12-14 14:25:00");
Createmap.put ("EndTime", "2017-12-15 14:25:00");

Get method call
String urlget = Urlget (Httporgcreatetest, Createmap, CharSet);
SYSTEM.OUT.PRINTLN ("xxx" +urlget);
}

/*

Maven Import Rack Package

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>

*/


}

HTTP tool classes for Java

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.