HTTPConnection.java 4.87 KB
/**
 * This file is a part of EpnTAPClient.
 * This program aims to provide EPN-TAP support for software clients, like CASSIS spectrum analyzer.
 * See draft specifications: https://voparis-confluence.obspm.fr/pages/viewpage.action?pageId=559861
 * Copyright (C) 2016 Institut de Recherche en Astrophysique et Planétologie.
 * 
 * This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or (at your option) any later
 * version. This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE. See the GNU General Public License for more details. You should have received a copy of
 * the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package eu.omp.irap.vespa.epntapclient.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;

import javax.net.ssl.HttpsURLConnection;

import eu.omp.irap.vespa.epntapclient.utils.Const;
import eu.omp.irap.vespa.epntapclient.utils.Err;
import eu.omp.irap.vespa.epntapclient.utils.Log;

/**
 * This class provide HTTP connection support to send requests through POST / GET protocols.
 * 
 * @author N. Jourdane
 */
public class HTTPConnection {
	/** The user agent used for the requests. */
	private final static String USER_AGENT = "Mozilla/5.0"; //$NON-NLS-1$

	/**
	 * @param url The target URL of the request.
	 * @param urlParameters The parameters of the request.
	 * @param resultFileName The name of the file where the request response content is writed.
	 * @return The response code of the request (200 if successful).
	 */
	public static int sendGet(String url, String urlParameters, String resultFileName) {
		String inputLine;
		StringBuffer response = new StringBuffer();
		URL obj;
		int responseCode = -1;
		BufferedReader in;

		try {
			obj = new URL(url + "?" + urlParameters); //$NON-NLS-1$
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
			con.setRequestMethod("GET"); //$NON-NLS-1$

			// add request header
			con.setRequestProperty("User-Agent", USER_AGENT); //$NON-NLS-1$
			responseCode = con.getResponseCode();
			in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
		} catch (IOException e1) {
			Log.LOGGER.log(Level.SEVERE, Err.BAD_REQUEST, e1);
		}

		printRequestResult(response, resultFileName);

		return responseCode;
	}

	/**
	 * @param url The target URL of the request.
	 * @param urlParameters The parameters of the request.
	 * @param resultFileName The name of the file where the request response content is writed.
	 * @return The response code of the request (200 if successful).
	 */
	public static int sendPost(String url, String urlParameters, String resultFileName) {

		URL obj;
		StringBuffer response = new StringBuffer();
		int responseCode = -1;
		DataOutputStream wr;
		BufferedReader in;

		try {
			obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

			// Add request header
			con.setRequestMethod("POST"); //$NON-NLS-1$
			con.setRequestProperty("User-Agent", USER_AGENT); //$NON-NLS-1$
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //$NON-NLS-1$ //$NON-NLS-2$

			con.setDoOutput(true);
			wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();
			responseCode = con.getResponseCode();
			in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
		} catch (IOException e1) {
			Log.LOGGER.log(Level.SEVERE, Err.BAD_REQUEST, e1);
		}

		printRequestResult(response, resultFileName);

		return responseCode;
	}

	/**
	 * Try to print result in resultfileName.
	 * 
	 * @param response The request response content.
	 * @param resultFileName The name of the file where the request response content is writed.
	 */
	private static void printRequestResult(StringBuffer response, String resultFileName) {
		PrintWriter writer;

		try {
			writer = new PrintWriter(resultFileName, Const.CHARACTER_SET);
			writer.println(response);
			writer.close();
		} catch (FileNotFoundException e1) {
			Log.LOGGER.log(Level.SEVERE, Err.NOT_FOUND + resultFileName, e1);
		} catch (UnsupportedEncodingException e2) {
			Log.LOGGER.log(Level.SEVERE, Err.WRONG_ENCODING + Const.CHARACTER_SET, e2);
		}
	}
}