package com.loodos.Outrun;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.google.gson.Gson;
import android.view.View.OnTouchListener;
public class HttpRequest {
String requestUrl;
Boolean isPost;
Boolean reqSent = false;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
public HttpRequest(String requestUrl, Boolean isPost) {
this.requestUrl = requestUrl;
this.isPost = isPost;
}
public void AddParam(String key, String value) {
nameValuePairs.add(new BasicNameValuePair(key, value));
}
public void RemoveParam(String key) {
nameValuePairs.remove(key);
}
public void CleanParams() {
nameValuePairs.clear();
}
public HttpRequest() {
}
public void SendRequest() {
Thread thread = new RequestThread();
thread.start();
reqSent = true;
}
private class RequestThread extends Thread {
@Override
public void run() {
DoRequest();
}
}
private void DoRequest() {
InputStream is = getJSONData(requestUrl);
if (is != null) {
for (HttpEventListener item : httpEventListeners) {
item.OnHttpRequestFinished(is);
}
}
else
{
for (HttpEventListener item : httpEventListeners) {
item.OnHttpRequestError();
}
}
}
public InputStream DoSynchReq() {
InputStream is = getJSONData(requestUrl);
return is;
}
ArrayList<HttpEventListener> httpEventListeners = new ArrayList<HttpEventListener>();
public void addReqFinishListener(HttpEventListener listener) {
httpEventListeners.add(listener);
}
public void removeReqFinishListener(HttpEventListener listener) {
httpEventListeners.remove(listener);
}
public void SendRequest(String requestUrl, Boolean isPost) {
this.requestUrl = requestUrl;
this.isPost = isPost;
SendRequest();
}
public InputStream getJSONData(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri;
InputStream data = null;
try {
if (!isPost) {
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response = httpClient.execute(method);
data = response.getEntity().getContent();
} else {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
data = response.getEntity().getContent();
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
}