Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. package de.profiag.opentransport.rpcapi;
  2.  
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.ResponseHandler;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.StringEntity;
  9. import org.apache.http.impl.client.BasicResponseHandler;
  10. import org.apache.http.impl.client.HttpClientBuilder;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.net.URI;
  14. import java.net.URISyntaxException;
  15.  
  16. /*
  17. * Simple HttpRequest class that sends a POST request to the specified url and port.
  18. * Currently data is set to be of type application/json in the header.
  19. *
  20. * This class can easily be modified to send any other kind of http request and uses Apache's Http Client.
  21. * Refer to Apache Doc for more information about the used imports.
  22. *
  23. */
  24. public class HttpRequest {
  25. private HttpResponse httpResponse;
  26.  
  27. /*
  28. * Class Constructor
  29. *
  30. * Configures and sends the HTTP Request
  31. *
  32. * @param url destination URI to request is sent to
  33. * @param port open port at the given URI
  34. * @param data json object
  35. */
  36. public HttpRequest(String url, int port, String data) throws URISyntaxException {
  37. try {
  38. URI address = new URI("http", null, url, port, "", "id=10", "anchor");
  39. HttpPost request = new HttpPost(address);
  40. request.addHeader("content-type", "application/json");
  41. HttpEntity httpEntity = new StringEntity(data);
  42. request.setEntity(httpEntity);
  43. HttpClient httpClient = HttpClientBuilder.create().build();
  44. this.httpResponse = httpClient.execute(request);
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49.  
  50. /*
  51. * getResponse() function and returns the Response as InputStream
  52. *
  53. * @return response as InputStream
  54. */
  55. public InputStream getResponse() throws IOException {
  56. return this.httpResponse.getEntity().getContent();
  57. }
  58.  
  59. /*
  60. * getResponse() function and returns the Response as HttpResponse
  61. *
  62. * @return response as HttpResponse
  63. */
  64. public HttpResponse getResponseAsHttpResponse() {
  65. return this.httpResponse;
  66. }
  67.  
  68. /*
  69. * getBody() function and returns the Response's Body as String
  70. *
  71. * @return response as HttpResponse
  72. */
  73. public String getBody() throws IOException {
  74. ResponseHandler<String> handler = new BasicResponseHandler();
  75.  
  76. return handler.handleResponse(httpResponse);
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement