io.konverge.library.Request Maven / Gradle / Ivy
/**
* Copyright (C) 2009-2013 Nasrollah Kavian - All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser 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 io.konverge.library;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Random;
final class Request {
protected static Random s_random = new Random();
protected String m_address = "";
private final HashMap m_parameters = new HashMap();
protected String m_response = "";
protected int m_statusCode = 0;
public static final String encode(final String value) {
try {
return URLEncoder.encode(value, "UTF-8");
}
catch(final UnsupportedEncodingException e) {
}
return "";
}
protected Request(final String address) {
final String folder = address.substring(0, address.lastIndexOf("/"));
final String filename = address.substring(address.lastIndexOf("/") + 1);
m_address = folder + "/" + encode(filename).replace("+", "%20");
}
public Request execute() {
setParameter("_random_", "" + s_random.nextLong());
try {
final URL url = new URL(m_address);
final URLConnection connection = url.openConnection();
connection.setDoOutput(true);
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(Utility.join(m_parameters, "=", "&"));
writer.flush();
m_response = Utility.toString(connection.getInputStream());
m_statusCode = 200;
//System.out.println("----------- " + m_address + "\n\n----------- " + m_response);
writer.close();
}
catch(final Exception ignore) {
//ignore.printStackTrace();
}
return this;
}
public String getResponse() {
return m_response;
}
public int getStatusCode() {
return m_statusCode;
}
public Request setParameter(final String name, final double value) {
setParameter(name, "" + value);
return this;
}
public Request setParameter(final String name, final long value) {
setParameter(name, "" + value);
return this;
}
public Request setParameter(final String name, final String value) {
m_parameters.put(encode(name), value != null ? encode(value) : "");
return this;
}
}