package com.jerrychin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

public abstract class AbstractWebServiceProvider implements Provider {
	private Map<String, String> headers;
	@SuppressWarnings("unused")
	private Map<String, String> parameters;
	private URL url;

	private HttpURLConnection conn;

	AbstractWebServiceProvider(URL url, Map<String, String> headers) throws Exception {
		this.headers = headers;

		// URL itself has no knowledge of encoding, as stated in the official
		// document,
		// we need to encode the parameter before creating the URL instance.
		this.url = new URL(url.toURI().toASCIIString());
	}

	AbstractWebServiceProvider(URL url, Map<String, String> headers, Map<String, String> parameters) throws Exception {
		this(url, headers);

		// only used with POST
		this.parameters = parameters;
	}

	public AbstractWebServiceProvider get() throws IOException {
		// Notice: the real connection has NOT established yet after the
		// following call to openConnection.
		conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");

		// add/modify headers
		for (Entry<String, String> entry : headers.entrySet()) {
			conn.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
		}

		return this;
	}

	public AbstractWebServiceProvider post() throws ProtocolException {
		throw new UnsupportedOperationException("Method is not implemented yet.");
	}

	public WebService getService() {
		return new WebService() {dddddddddd
			@Override
			public String request() throws IOException {
				try(BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
					StringBuffer sb = new StringBuffer();
					String inputLine;
					while ((inputLine = in.readLine()) != null)
						sb.append(inputLine);
					return sb.toString();
				} finally {
					if (conn != null) {
				        conn.disconnect();
				    }
				}
			}
		};

	}
}

@@ -184,32 +184,54 @@
 ocolException;%0D%0A
+import java.net.URI;%0D%0A
 import java.net.
@@ -550,35 +550,38 @@
 ServiceProvider(
-URL
+String
  url, Map%3CString
@@ -646,16 +646,137 @@
 aders;%0D%0A
+%09%09%0D%0A%09%09if(url == null %7C%7C url.length() == 0)%0D%0A%09%09%09throw new NullPointerException(%22URL to web service cannot be empty!%22);%0D%0A%09%09
 %0D%0A%09%09// U
@@ -955,18 +955,19 @@
 URL(
-url.to
+new 
 URI(
+url
 ).to
@@ -1017,19 +1017,22 @@
 rovider(
-URL
+String
  url, Ma
@@ -1873,18 +1873,8 @@
 () %7B
-dddddddddd
 %0D%0A%09%09

make a nicer constructor.