All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xwzhou.commons.net.Connection Maven / Gradle / Ivy

The newest version!
package com.xwzhou.commons.net;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import com.xwzhou.commons.io.IOUtils;

public class Connection {

	public static enum Method {
		PUT, GET
	}

	private Request req = new Request();
	private Response res = new Response();

	public Connection url(URL url) {
		return null;
	}

	public Connection url(String url) {
		return null;
	}

	public Connection timeout(int millis) {
		req.timeout = millis;
		return this;
	}

	public Connection data(Map data) {
		return null;
	}

	public Connection data(String data) {
		return null;
	}

	public Connection data(byte[] data) {
		return null;
	}

	Response execute() throws Exception {
		final HttpURLConnection conn = (HttpURLConnection) (req.proxy == null ? req.url.openConnection()
				: req.url.openConnection(req.proxy));
		conn.setRequestMethod(req.method.name());
		conn.setInstanceFollowRedirects(false);
		conn.setConnectTimeout(req.timeout);
		conn.setReadTimeout(req.timeout);

		if (conn instanceof HttpsURLConnection) {

		}
		if (null != req.data) {
			conn.setDoOutput(true);
		}
		conn.connect();
		if (conn.getResponseCode() == 200) {
			res.body = IOUtils.toString(conn.getInputStream());
		}
		return res;
	}

	private static URL resolve(URL base, String relUrl) throws MalformedURLException {
		if (relUrl.startsWith("?"))
			relUrl = base.getPath() + relUrl;
		if (relUrl.indexOf('.') == 0 && base.getFile().indexOf('/') != 0) {
			base = new URL(base.getProtocol(), base.getHost(), base.getPort(), "/" + base.getFile());
		}
		return new URL(base, relUrl);
	}

	public static class Response {
		String body;
		public String getBody() {
			return body;
		}
	}

	public static class Request {
		public static final int TIMEOUT = 10000;
		URL url;
		Proxy proxy;
		int timeout = TIMEOUT;
		Method method = Method.GET;
		String param;
		byte[] data;

		void prepare() {
			if (Method.GET.equals(method)) {
				data = null;
			}
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy