diff --git a/src/org/janis/http/Fetcher.java b/src/org/janis/http/Fetcher.java new file mode 100644 index 0000000..353e530 --- /dev/null +++ b/src/org/janis/http/Fetcher.java @@ -0,0 +1,93 @@ +/* + * @author Onur Avsar + */ +package org.janis.http; + +import java.io.IOException; +import java.net.URLEncoder; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; + +public class Fetcher { + + private HttpClient mHttpClient; + private HttpGet mHttpGet; + private HttpResponse mHttpResponse; + private String url; + + /** + * @param url the URL + */ + public Fetcher(String url) { + this.url = url; + mHttpClient = new DefaultHttpClient(); + } + + /** + * @return the result + */ + public String fetch() throws ClientProtocolException, IOException { + mHttpGet = new HttpGet(url); + mHttpResponse = mHttpClient.execute(mHttpGet); + String result = EntityUtils.toString(mHttpResponse.getEntity()); + return result; + } + + /** + * @param nameValuePairs the mNameValuePairs to create parameters + * @return the result + */ + public String fetch(NameValuePair[] nameValuePairs) throws ClientProtocolException, IOException { + StringBuffer encodedParameters = new StringBuffer("?"); + for (NameValuePair nameValuePair: nameValuePairs) { + encodedParameters.append(URLEncoder.encode(nameValuePair.getName()) + "=" + URLEncoder.encode(nameValuePair.getValue()) + "&"); + } + encodedParameters.deleteCharAt(encodedParameters.length() - 1); + url += encodedParameters; + mHttpGet = new HttpGet(url); + mHttpResponse = mHttpClient.execute(mHttpGet); + String result = EntityUtils.toString(mHttpResponse.getEntity()); + return result; + } + + /** + * @return the mHttpClient + */ + public HttpClient getHttpClient() { + return mHttpClient; + } + + /** + * @param mHttpClient the mHttpClient to set + */ + public void setHttpClient(HttpClient httpClient) { + this.mHttpClient = httpClient; + } + + /** + * @return the URL + */ + public String getUrl() { + return url; + } + + /** + * @param url the URL to set + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * @return the mHttpResponse + */ + public HttpResponse getHttpResponse() { + return mHttpResponse; + } +}