Subversion Repositories SmartDukaan

Rev

Rev 37388 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21557 ashik.ali 1
package com.spice.profitmandi.common.web.client;
2
 
30289 amit.gupta 3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.spice.profitmandi.common.ResponseCodeHolder;
5
import com.spice.profitmandi.common.enumuration.SchemeType;
6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
37661 amit 7
import com.spice.profitmandi.common.model.RawHttpResponse;
21557 ashik.ali 8
import org.apache.http.HttpResponse;
22215 ashik.ali 9
import org.apache.http.NameValuePair;
21557 ashik.ali 10
import org.apache.http.client.ClientProtocolException;
11
import org.apache.http.client.HttpClient;
25244 amit.gupta 12
import org.apache.http.client.config.RequestConfig;
22215 ashik.ali 13
import org.apache.http.client.entity.UrlEncodedFormEntity;
34805 ranu 14
import org.apache.http.client.methods.*;
23502 ashik.ali 15
import org.apache.http.conn.HttpHostConnectException;
16
import org.apache.http.entity.ContentType;
17
import org.apache.http.entity.StringEntity;
34805 ranu 18
import org.apache.http.impl.client.CloseableHttpClient;
25244 amit.gupta 19
import org.apache.http.impl.client.HttpClientBuilder;
21557 ashik.ali 20
import org.apache.http.impl.client.HttpClients;
30383 amit.gupta 21
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
22215 ashik.ali 22
import org.apache.http.message.BasicNameValuePair;
34805 ranu 23
import org.apache.http.util.EntityUtils;
25011 amit.gupta 24
import org.apache.logging.log4j.LogManager;
23568 govind 25
import org.apache.logging.log4j.Logger;
25726 amit.gupta 26
import org.springframework.beans.factory.annotation.Autowired;
21557 ashik.ali 27
import org.springframework.http.HttpStatus;
23526 ashik.ali 28
import org.springframework.stereotype.Component;
21557 ashik.ali 29
import org.springframework.web.util.UriComponentsBuilder;
30
 
30289 amit.gupta 31
import java.io.*;
32
import java.util.ArrayList;
33
import java.util.List;
34
import java.util.Map;
35
import java.util.Set;
21557 ashik.ali 36
 
23526 ashik.ali 37
@Component
21557 ashik.ali 38
public class RestClient {
25011 amit.gupta 39
 
31828 amit.gupta 40
    private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 41
 
31828 amit.gupta 42
    private HttpClient httpClient;
25011 amit.gupta 43
 
30289 amit.gupta 44
 
31828 amit.gupta 45
    @Autowired
46
    ObjectMapper objectMapper;
25726 amit.gupta 47
 
31828 amit.gupta 48
    public RestClient() {
49
        PoolingHttpClientConnectionManager connManager
50
                = new PoolingHttpClientConnectionManager();
36416 amit 51
        connManager.setMaxTotal(20);
52
        connManager.setDefaultMaxPerRoute(8);
31828 amit.gupta 53
        httpClient = HttpClients.custom().disableCookieManagement().disableAuthCaching().disableConnectionState().
36416 amit 54
                disableAuthCaching().setConnectionManager(connManager)
55
                .setDefaultRequestConfig(HttpClientFactory.defaultRequestConfig())
56
                .build();
25244 amit.gupta 57
 
31828 amit.gupta 58
    }
25011 amit.gupta 59
 
31828 amit.gupta 60
    public RestClient(int connectionTimeoutMillis) {
36416 amit 61
        this.httpClient = HttpClientBuilder.create().disableCookieManagement()
62
                .setDefaultRequestConfig(HttpClientFactory.defaultRequestConfig()).build();
25244 amit.gupta 63
 
31828 amit.gupta 64
    }
25244 amit.gupta 65
 
37321 amit 66
    /**
67
     * RestClient on a caller-supplied timeout profile from {@link HttpClientFactory}. Not a
68
     * Spring bean — construct it explicitly where a non-default timeout is justified, and pass
69
     * the ObjectMapper in, since field injection does not apply to hand-built instances.
70
     */
71
    public RestClient(RequestConfig requestConfig, ObjectMapper objectMapper) {
72
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
73
        connManager.setMaxTotal(20);
74
        connManager.setDefaultMaxPerRoute(8);
75
        this.httpClient = HttpClients.custom().disableCookieManagement().disableAuthCaching()
76
                .disableConnectionState().setConnectionManager(connManager)
77
                .setDefaultRequestConfig(requestConfig)
78
                .build();
79
        this.objectMapper = objectMapper;
80
    }
81
 
31828 amit.gupta 82
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
83
                      Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
84
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
85
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
86
        return this.get(url, params, headers);
87
    }
25011 amit.gupta 88
 
31828 amit.gupta 89
    public String get(String url, Map<String, String> params, Map<String, String> headers)
90
            throws ProfitMandiBusinessException, HttpHostConnectException {
91
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
92
        if (params != null) {
93
            Set<String> keys = params.keySet();
94
            for (String key : keys) {
95
                builder.queryParam(key, params.get(key));
96
            }
97
        }
98
        HttpGet request = new HttpGet(builder.build().encode().toUri());
99
        if (headers != null) {
100
            for (Map.Entry<String, String> entry : headers.entrySet()) {
101
                request.setHeader(entry.getKey(), entry.getValue());
102
            }
103
        }
104
        return this.execute(request);
105
    }
22233 amit.gupta 106
 
37388 vikas 107
    /**
108
     * GET that returns the response body whatever the status code, rather than throwing and discarding
109
     * it as {@link #get(String, Map, Map)} does.
110
     *
111
     * <p>Use this against APIs that report their errors in a JSON body: with {@code get} a rejected
112
     * request surfaces as an exception carrying no detail, so the reason for the failure is lost. This
113
     * is the GET counterpart of {@link #postJson(String, Object, Map)}.</p>
114
     */
115
    public String getJson(String url, Map<String, String> params, Map<String, String> headers)
116
            throws ProfitMandiBusinessException, HttpHostConnectException {
117
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
118
        if (params != null) {
119
            Set<String> keys = params.keySet();
120
            for (String key : keys) {
121
                builder.queryParam(key, params.get(key));
122
            }
123
        }
124
        HttpGet request = new HttpGet(builder.build().encode().toUri());
125
        if (headers != null) {
126
            for (Map.Entry<String, String> entry : headers.entrySet()) {
127
                request.setHeader(entry.getKey(), entry.getValue());
128
            }
129
        }
130
        return this.executeJson(request);
131
    }
132
 
31828 amit.gupta 133
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
134
            throws ProfitMandiBusinessException, HttpHostConnectException {
135
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
136
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
137
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
138
        if (params != null) {
139
            Set<String> keys = params.keySet();
140
            for (String key : keys) {
141
                builder.queryParam(key, params.get(key));
142
            }
143
        }
144
        HttpGet request = new HttpGet(builder.build().encode().toUri());
145
        return this.execute(request);
146
    }
25011 amit.gupta 147
 
31828 amit.gupta 148
    public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
149
            throws ProfitMandiBusinessException, HttpHostConnectException {
150
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
151
        if (params != null) {
152
            for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
153
                builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
154
            }
30289 amit.gupta 155
 
31828 amit.gupta 156
        }
157
        HttpGet request = new HttpGet(builder.build().encode().toUri());
158
        if (headers != null) {
159
            for (Map.Entry<String, String> entry : headers.entrySet()) {
160
                request.setHeader(entry.getKey(), entry.getValue());
161
            }
162
        }
163
        try {
164
            LOGGER.info("Request uri is  {}", request.getURI().toString());
165
            HttpResponse response = httpClient.execute(request);
166
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
167
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
168
                return response;
169
            } else {
170
                throw new ProfitMandiBusinessException("", "", "GE_1005");
171
            }
172
        } catch (HttpHostConnectException httpHostConnectException) {
173
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
174
            throw httpHostConnectException;
175
        } catch (ClientProtocolException e) {
176
            LOGGER.error("Client Error : ", e);
37321 amit 177
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 178
        } catch (IOException e) {
179
            LOGGER.error("IO Error : ", e);
37321 amit 180
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 181
        }
182
    }
25011 amit.gupta 183
 
31828 amit.gupta 184
    public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
185
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 186
        HttpResponse response = null;
31828 amit.gupta 187
        try {
36295 amit 188
            response = httpClient.execute(request);
31828 amit.gupta 189
            String responseString = this.toString(response.getEntity().getContent());
190
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
191
            LOGGER.info("Response String {}", responseString);
34877 ranu 192
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()  || response.getStatusLine().getStatusCode() == HttpStatus.CREATED.value() || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value()) {
31828 amit.gupta 193
                return responseString;
194
            } else {
195
                LOGGER.info("Response String {} ", responseString);
196
                throw new ProfitMandiBusinessException("", "", "GE_1005");
197
            }
198
        } catch (HttpHostConnectException httpHostConnectException) {
199
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
200
            throw httpHostConnectException;
201
        } catch (ClientProtocolException e) {
202
            LOGGER.error("Client Error : ", e);
37321 amit 203
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 204
        } catch (IOException e) {
205
            LOGGER.error("IO Error : ", e);
37321 amit 206
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 207
        } finally {
208
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 209
        }
210
    }
25011 amit.gupta 211
 
37661 amit 212
    public RawHttpResponse executeRaw(HttpUriRequest request)
31828 amit.gupta 213
            throws ProfitMandiBusinessException, HttpHostConnectException {
214
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 215
        HttpResponse response = null;
31828 amit.gupta 216
        try {
36295 amit 217
            response = httpClient.execute(request);
31828 amit.gupta 218
            String responseString = this.toString(response.getEntity().getContent());
219
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
29834 tejbeer 220
 
37661 amit 221
            RawHttpResponse rawResponse = new RawHttpResponse();
222
            rawResponse.setResponseString(responseString);
223
            rawResponse.setStatusCode(response.getStatusLine().getStatusCode());
29834 tejbeer 224
 
37661 amit 225
            return rawResponse;
31828 amit.gupta 226
        } catch (HttpHostConnectException httpHostConnectException) {
227
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
228
            throw httpHostConnectException;
229
        } catch (ClientProtocolException e) {
230
            LOGGER.error("Client Error : ", e);
37321 amit 231
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 232
        } catch (IOException e) {
233
            LOGGER.error("IO Error : ", e);
37321 amit 234
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 235
        } finally {
236
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 237
        }
238
    }
29834 tejbeer 239
 
31828 amit.gupta 240
    public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
241
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 242
        HttpResponse response = null;
31828 amit.gupta 243
        try {
36295 amit 244
            response = httpClient.execute(request);
31828 amit.gupta 245
            String responseString = this.toString(response.getEntity().getContent());
246
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
247
            LOGGER.info("Response String {}", responseString);
248
            return responseString;
249
        } catch (HttpHostConnectException httpHostConnectException) {
250
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
251
            throw httpHostConnectException;
252
        } catch (ClientProtocolException e) {
253
            LOGGER.error("Client Error : ", e);
37321 amit 254
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 255
        } catch (IOException e) {
256
            LOGGER.error("IO Error : ", e);
37321 amit 257
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 258
        } finally {
259
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 260
        }
261
    }
27179 amit.gupta 262
 
35623 amit 263
    public HttpResponse postResponse(String url, Map<String, String> params, Map<String, String> headers)
264
            throws ProfitMandiBusinessException, HttpHostConnectException {
265
        List<NameValuePair> bodyParameters = new ArrayList<>();
266
        if (params != null) {
267
            for (Map.Entry<String, String> entry : params.entrySet()) {
268
                bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
269
            }
270
        }
271
        HttpPost request = new HttpPost(url);
272
        if (headers != null) {
273
            for (Map.Entry<String, String> entry : headers.entrySet()) {
274
                request.setHeader(entry.getKey(), entry.getValue());
275
            }
276
        }
277
        try {
278
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
279
            LOGGER.info("Request uri is  {}", request.getURI().toString());
280
            HttpResponse response = httpClient.execute(request);
281
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
282
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
283
                return response;
284
            } else {
285
                throw new ProfitMandiBusinessException("", "", "GE_1005");
286
            }
287
        } catch (HttpHostConnectException httpHostConnectException) {
288
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
289
            throw httpHostConnectException;
290
        } catch (ClientProtocolException e) {
291
            LOGGER.error("Client Error : ", e);
37321 amit 292
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
35623 amit 293
        } catch (IOException e) {
294
            LOGGER.error("IO Error : ", e);
37321 amit 295
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
35623 amit 296
        }
297
    }
298
 
31828 amit.gupta 299
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
300
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
301
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
302
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
303
        return this.post(url, params, headers);
304
    }
25011 amit.gupta 305
 
31828 amit.gupta 306
    public String post(String url, Map<String, String> params, Map<String, String> headers)
307
            throws ProfitMandiBusinessException, HttpHostConnectException {
308
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
309
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
310
        for (Map.Entry<String, String> entry : params.entrySet()) {
311
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
312
        }
25011 amit.gupta 313
 
31828 amit.gupta 314
        LOGGER.info("Body Parameters {}", params);
315
        HttpPost request = new HttpPost(url);
316
        for (Map.Entry<String, String> entry : headers.entrySet()) {
317
            request.setHeader(entry.getKey(), entry.getValue());
318
        }
25011 amit.gupta 319
 
31828 amit.gupta 320
        try {
321
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
322
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
323
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
324
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
325
        }
25011 amit.gupta 326
 
31828 amit.gupta 327
        return this.execute(request);
25011 amit.gupta 328
 
31828 amit.gupta 329
    }
25011 amit.gupta 330
 
31828 amit.gupta 331
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
332
            throws ProfitMandiBusinessException, HttpHostConnectException {
333
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
334
        if (queryParams != null) {
335
            Set<String> keys = queryParams.keySet();
336
            for (String key : keys) {
337
                builder.queryParam(key, queryParams.get(key));
338
            }
339
        }
340
        List<NameValuePair> bodyParameters = new ArrayList<>();
341
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
342
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
343
        }
28653 amit.gupta 344
 
31828 amit.gupta 345
        HttpPost request = new HttpPost(builder.build().encode().toUri());
346
        for (Map.Entry<String, String> entry : headers.entrySet()) {
347
            request.setHeader(entry.getKey(), entry.getValue());
348
        }
28653 amit.gupta 349
 
31828 amit.gupta 350
        try {
351
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
352
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
353
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
354
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
355
        }
28653 amit.gupta 356
 
31828 amit.gupta 357
        return this.execute(request);
28653 amit.gupta 358
 
31828 amit.gupta 359
    }
25011 amit.gupta 360
 
31828 amit.gupta 361
    public String post(String url, String body, Map<String, String> headers)
362
            throws ProfitMandiBusinessException, HttpHostConnectException {
363
        HttpPost request = new HttpPost(url);
364
        for (Map.Entry<String, String> entry : headers.entrySet()) {
365
            request.setHeader(entry.getKey(), entry.getValue());
366
        }
25726 amit.gupta 367
 
31828 amit.gupta 368
        try {
369
            request.setEntity(new StringEntity(body));
370
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
371
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
372
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
373
        }
29834 tejbeer 374
 
31828 amit.gupta 375
        return this.execute(request);
29834 tejbeer 376
 
31828 amit.gupta 377
    }
29834 tejbeer 378
 
31828 amit.gupta 379
    public String postJson(String url, Object object, Map<String, String> headers)
380
            throws ProfitMandiBusinessException, HttpHostConnectException {
381
        String jsonString;
382
        try {
383
            if (object.getClass().equals(String.class)) {
384
                jsonString = (String) object;
385
            } else {
386
                jsonString = objectMapper.writeValueAsString(object);
387
            }
388
            LOGGER.info("JSON String - {}", jsonString);
389
        } catch (Exception e) {
390
            e.printStackTrace();
391
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
392
        }
393
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 394
 
31828 amit.gupta 395
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 396
 
31828 amit.gupta 397
        HttpPost request = new HttpPost(builder.build().encode().toUri());
398
        for (Map.Entry<String, String> entry : headers.entrySet()) {
399
            request.setHeader(entry.getKey(), entry.getValue());
400
        }
401
        request.setEntity(requestEntity);
402
        return this.executeJson(request);
403
    }
404
 
37661 amit 405
    public RawHttpResponse postWithResponse(String url, String body, Map<String, String> headers)
36200 ranu 406
            throws ProfitMandiBusinessException, HttpHostConnectException {
407
        HttpPost request = new HttpPost(url);
408
        for (Map.Entry<String, String> entry : headers.entrySet()) {
409
            request.setHeader(entry.getKey(), entry.getValue());
410
        }
411
        try {
412
            request.setEntity(new StringEntity(body));
413
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
414
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
415
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
416
        }
37661 amit 417
        return this.executeRaw(request);
36200 ranu 418
    }
419
 
31828 amit.gupta 420
    public String patchJson(String url, Object object, Map<String, String> headers)
421
            throws ProfitMandiBusinessException, HttpHostConnectException {
422
        String jsonString;
423
        try {
424
            if (object.getClass().equals(String.class)) {
425
                jsonString = (String) object;
426
            } else {
427
                jsonString = objectMapper.writeValueAsString(object);
428
            }
429
            LOGGER.info("JSON String - {}", jsonString);
430
        } catch (Exception e) {
431
            e.printStackTrace();
432
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
433
        }
434
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
435
 
436
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
437
 
438
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
439
        for (Map.Entry<String, String> entry : headers.entrySet()) {
440
            request.setHeader(entry.getKey(), entry.getValue());
441
        }
442
        request.setEntity(requestEntity);
443
        return this.executeJson(request);
444
    }
445
 
446
    private String toString(InputStream inputStream) {
447
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
448
        StringBuilder responseString = new StringBuilder();
449
        String line = null;
450
        try {
451
            while ((line = reader.readLine()) != null) {
452
                responseString.append(line);
453
            }
454
            inputStream.close();
455
        } catch (IOException e) {
456
            throw new RuntimeException();
457
        }
458
        return responseString.toString();
459
    }
34805 ranu 460
 
461
    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
462
        HttpPost post = new HttpPost(url);
463
        headers.forEach(post::setHeader);
464
 
465
        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
466
 
36416 amit 467
        try (CloseableHttpClient client = HttpClientFactory.apacheHttp();
34805 ranu 468
             CloseableHttpResponse response = client.execute(post)) {
469
 
470
            int statusCode = response.getStatusLine().getStatusCode();
471
            if (statusCode != 200) {
472
                throw new IOException("Failed : HTTP error code : " + statusCode);
473
            }
474
 
475
            return EntityUtils.toByteArray(response.getEntity());
476
        }
477
    }
478
 
21557 ashik.ali 479
}