Creato da pastuweb.com
Share My Page
My Social Accounts
Account FaceBook Account LinkedIn Account Twitter Account Google Plus Account Git Hub

In questa classe Java mostro alcuni metodi statici per l'invio ad URL specifiche (esterne o interne) dei parametri all'interno di una POST.

I parametri possono essere dei semplici valori oppure un XML.

Analizzando la classe noterete che ci sono diversi modi per fare una POST:
  • Classica senza Authorization

  • Con Authorization Basic in Base64 di user+password

  • Con Authorization Basic in Base64 di user+password + SSL (con i certificati che ci sono sul server web)

 
package javautility.utility;
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
 
import org.apache.log4j.Logger;
 
public class HTTPUtil {
 
private static Logger log = Logger.getLogger(Config.class);
 
public static URL getURL(String endpoint) throws MalformedURLException {
return new URL(endpoint);
}
 
 
public static String sendPost(URL url, Map<String,String> parameterMap){
 
String response = "";
try {
       // Construct data
String data = new String ();
for (String key : parameterMap.keySet()){
data += URLEncoder.encode(key, "UTF-8") + "=" +
URLEncoder.encode(parameterMap.get(key), "UTF-8");
data += "&";
};
// elimino & finale
data = data.substring(0, data.length()-1);
   
       // Send data
       URLConnection conn = url.openConnection();
       conn.setDoOutput(true);
       OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
       wr.write(data);
       wr.flush();
 
       // Get the response
       BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
       Map<String, List<String>> heaerFields = conn.getHeaderFields();
       Set<String> headerSet = heaerFields.keySet();
       for (String header : headerSet) {
log.debug(header +" :" + heaerFields.get(header));
}
       String line;
       while ((line = rd.readLine()) != null) {
        response = response + line; 
       }
       log.debug("body: " +response);
       wr.close();
       rd.close();
   } catch (Exception e) {
    log.error("Error to send HTTP post", e);
   }
   
   return response;
 
}
 
 
public static String sendAuthPost(URL url, String authorization,
Map<String, String> parameterMap) {
String buffer = null;
String res = "";
try {
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;
 
// Construct data
String data = new String();
for (String key : parameterMap.keySet()) {
data += URLEncoder.encode(key, "UTF-8") + "="
+ URLEncoder.encode(parameterMap.get(key), "UTF-8");
data += "&";
}
;
// elimino & finale
data = data.substring(0, data.length() - 1);
 
// Create connection
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Authorization", "Basic "
+ authorization);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""
+ data.length());
 
// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
 
// Send request
outStream.writeBytes(data);
outStream.flush();
outStream.close();
 
inStream = new DataInputStream(urlConnection.getInputStream());
// Get Response
// - For debugging purposes only!
while ((buffer = inStream.readLine()) != null) {
res += buffer;
log.debug(buffer);
}
 
// Close I/O streams
inStream.close();
outStream.close();
} catch (Exception ex) {
log.debug("Errore invio HTTP POST");
log.debug(ex);
buffer = ex.getMessage();
}finally{
 
return res;
 
}
 
}
 
 
public static String encodeParameter(String name, String value) throws Exception {
try {
return name+"="+URLEncoder.encode(value,"UTF-8");
} catch (Exception e) {
log.debug("Error to encode parameter "+ name);
throw e;
}
}
 
 
public static void sendXMLviaAuthPOST(String username, String pwd,
Map<String,Double> chiaveValoreMap, Date dataInvio) {
 
Map<String,String> parameters = new HashMap<String, String>();
 
// viene passata anche la Data di Invio, potrebbe essere utile
String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(dataInvio);
 
String XMLPacket = 
"<CustomXML>" +
/*vostri tag personalizzati con i valori presi dal Map parametro*/
"</CustomXML>";
 
log.info("invio XML per utente " + username);
log.info(XMLPacket);
 
parameters.put("XMLPacket", XMLPacket);
 
try{
 
URL urlService = new URL("http://url_al_quale_inviare");
String authorization = Base64.encode(username.toLowerCase()+":"+pwd);
HTTPUtil.sendAuthPost(urlService, authorization, parameters);
 
}catch (java.net.MalformedURLException ex){
 
log.info("Errore invio");
log.info(ex);
 
}
 
}
 
public static void sendAuthPostSSLAware(URL url, String authorization,
Map<String, String> parameterMap){
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
String str = "";
int flag = 1;
 
try {
Properties sysProperties = System.getProperties();
 
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
log.warn("Warning: URL Host: " + urlHostName
+ " vs. " + session.getPeerHost());
return true;
}
};
 
// Now you are telling the JRE to trust any https server.
// If you know the URL that you are connecting to then this should
// not be a problem
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
 
sendAuthPost(url, authorization, parameterMap);
 
} catch (MalformedURLException ex) {
log.error("Errore invio");
log.error(ex);
} catch (IOException ex) {
log.error("Errore invio");
log.error(ex);
} catch (Exception ex) {
log.error("Errore invio");
log.error(ex);
}
}
 
// Just add these two functions in your program
public static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
 
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
 
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
 
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
 
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
 
private static void trustAllHttpsCertificates() throws Exception {
 
// Create a trust manager that does not validate certificate chains:
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 
}
 
}
 
Average (1 Vote)
The average rating is 5.0 stars out of 5.