forked from karatelabs/karate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Consumer.java
executable file
·50 lines (42 loc) · 1.52 KB
/
Consumer.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
50
package payment.consumer;
import com.intuit.karate.FileUtils;
import com.intuit.karate.JsonUtils;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import payment.producer.Payment;
/**
*
* @author pthomas3
*/
public class Consumer {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
private final String paymentServiceUrl;
public Consumer(String paymentServiceUrl) {
this.paymentServiceUrl = paymentServiceUrl;
}
private HttpURLConnection getConnection(String path) throws Exception {
URL url = new URL(paymentServiceUrl + path);
return (HttpURLConnection) url.openConnection();
}
public Payment create(Payment payment) {
try {
HttpURLConnection con = getConnection("/payments");
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
String json = JsonUtils.toJson(payment);
IOUtils.write(json, con.getOutputStream(), "utf-8");
int status = con.getResponseCode();
if (status != 200) {
throw new RuntimeException("status code was " + status);
}
String content = FileUtils.toString(con.getInputStream());
return JsonUtils.fromJson(content, Payment.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}