76 lines
1.8 KiB
Java
76 lines
1.8 KiB
Java
|
package Classes;
|
||
|
|
||
|
import java.io.BufferedReader;
|
||
|
import java.io.DataOutputStream;
|
||
|
import java.io.IOException;
|
||
|
import java.io.InputStream;
|
||
|
import java.io.InputStreamReader;
|
||
|
import java.net.HttpURLConnection;
|
||
|
import java.net.URL;
|
||
|
import java.util.HashMap;
|
||
|
import java.util.Iterator;
|
||
|
import java.util.Map;
|
||
|
|
||
|
import Interfaces.Callback;
|
||
|
|
||
|
public class ApiCall implements Runnable {
|
||
|
|
||
|
private Callback callback;
|
||
|
private HttpURLConnection connection;
|
||
|
private String method;
|
||
|
|
||
|
public ApiCall(String URL, String method, Callback call) {
|
||
|
this.callback = call;
|
||
|
this.method = method;
|
||
|
try {
|
||
|
URL url = new URL(URL);
|
||
|
this.connection = (HttpURLConnection) url.openConnection();
|
||
|
this.connection.setRequestMethod(method);
|
||
|
this.connection.setDoInput(true);
|
||
|
this.connection.setDoOutput(true);
|
||
|
} catch (IOException e) {
|
||
|
System.out.println("Impossible d'ouvrir l'URL: "+URL);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void addHeaders(HashMap<String,String> map) {
|
||
|
Iterator it = map.entrySet().iterator();
|
||
|
while (it.hasNext()) {
|
||
|
Map.Entry pair = (Map.Entry)it.next();
|
||
|
this.connection.setRequestProperty((String)pair.getKey(), (String)pair.getValue());
|
||
|
it.remove(); // avoids a ConcurrentModificationException
|
||
|
}
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public void run() {
|
||
|
try {
|
||
|
//Send request
|
||
|
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
|
||
|
wr.flush ();
|
||
|
wr.close ();
|
||
|
|
||
|
//Get Response
|
||
|
InputStream is = connection.getInputStream();
|
||
|
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
|
||
|
String line;
|
||
|
StringBuffer response = new StringBuffer();
|
||
|
while((line = rd.readLine()) != null) {
|
||
|
response.append(line);
|
||
|
}
|
||
|
rd.close();
|
||
|
|
||
|
this.callback.call(response.toString());
|
||
|
|
||
|
} catch (IOException e) {
|
||
|
// TODO Auto-generated catch block
|
||
|
e.printStackTrace();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public void send() {
|
||
|
new Thread(this).start();
|
||
|
}
|
||
|
|
||
|
}
|