/
HttpAdapter.java
49 lines (43 loc) · 1.85 KB
/
HttpAdapter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package tr.edu.itu.cavabunga.client.http;
import tr.edu.itu.cavabunga.client.exception.ClientException;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Data
@Component
public class HttpAdapter {
public static String doRequest(String requestUrl, RequestMethod requestMethod, String bodyParameters){
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod.toString());
if(bodyParameters != null && !bodyParameters.isEmpty()){
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(bodyParameters);
out.flush();
out.close();
}
connection.setRequestProperty("Content-Type", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer result = new StringBuffer();
while((inputLine = in.readLine()) != null){
result.append(inputLine);
}
in.close();
connection.disconnect();
if(connection.getResponseCode() != 200){
throw new ClientException("Cavabunga server return with http code: " + connection.getResponseCode());
}
return result.toString();
}catch (Exception e){
throw new ClientException("There is a problem about http connection: " + e.getMessage());
}
}
}