@Override public <T, R extends ApiResponse<T>> PendingResult<T> handlePost( String hostName, String url, String payload, String userAgent, Class<R> clazz, FieldNamingPolicy fieldNamingPolicy, long errorTimeout, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10); HTTPRequest req = null; try { req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions); req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=utf-8")); req.setPayload(payload.getBytes(UTF_8)); } catch (MalformedURLException e) { LOG.error("Request: {}{}", hostName, url, e); throw (new RuntimeException(e)); } return new GaePendingResult<>( req, client, clazz, fieldNamingPolicy, errorTimeout, maxRetries, exceptionsAllowedToRetry); }
protected void writeRequestBody(GHttpEndpoint endpoint, Exchange exchange, HTTPRequest request) { request.setPayload(exchange.getIn().getBody(byte[].class)); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String code = req.getParameter("code"); URL fetchurl = new URL(url); HTTPRequest request = new HTTPRequest(fetchurl, HTTPMethod.POST); String body = "code=" + code + "&grant_type=authorization_code" + "&client_id=" + dropboKey + "&client_secret=" + dropboxSecret + "&redirect_uri=" + redirectUri; request.setPayload(body.getBytes("UTF-8")); HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request); String respInJson = new String(response.getContent()); LOGGER.warning(respInJson); JSONObject jsonObj; try { jsonObj = new JSONObject(respInJson); String uid=jsonObj.getString("uid"); String access_token=jsonObj.getString("access_token"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }
URL url = new URL(URBAN_AIRSHIP_API_URL); HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST); String authString = ApplicationProperties.getUrbanAirshipAppId() + ":" + ApplicationProperties.getUrbanAirshipMasterSecret(); String authStringBase64 = new String(Base64.encodeBase64(authString.getBytes())); authStringBase64 = authStringBase64.trim(); req.addHeader(new HTTPHeader("Content-Type", "application/json")); req.addHeader(new HTTPHeader("Authorization", "Basic " + authStringBase64)); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); mapper.writeValue(byteStream, new PushNotificationObj(userEmail, message)); req.setPayload(byteStream.toByteArray());
public static void addMultipartBodyToRequest(MultipartEntity entity, HTTPRequest req) throws IOException{ /* * turn Entity to byte[] using ByteArrayOutputStream */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); entity.writeTo(bos); byte[] body = bos.toByteArray(); /* * extract multipart boundary (body starts with --boundary\r\n) */ String boundary = new BufferedReader(new StringReader(new String(body))).readLine(); boundary = boundary.substring(2, boundary.length()); /* * add multipart header and body */ req.addHeader(new HTTPHeader("Content-type", "multipart/form-data; boundary=" + boundary)); req.setPayload(body); }
public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (request.getEntity() != null) { request.getEntity().writeTo(baos); } this.request.setPayload(baos.toByteArray()); }
public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (request.getEntity() != null) { request.getEntity().writeTo(baos); } this.request.setPayload(baos.toByteArray()); }
String json ="{}"; URL url = new URL("https://android.googleapis.com/gcm/send"); HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST); request.addHeader(new HTTPHeader("Content-Type","application/json")); request.addHeader(new HTTPHeader("Authorization", "key=<>")); request.setPayload(json.getBytes("UTF-8")); HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
@Override public Response finish() throws IOException { if (request == null) { throw new IllegalStateException("Uploader already closed."); } request.setPayload(body.toByteArray()); HTTPResponse response = service.fetch(request); Response requestorResponse = toRequestorResponse(response); close(); if (progressListener != null) { progressListener.onProgress(request.getPayload().length); } return requestorResponse; } }
httpRequest.addHeader(new HTTPHeader("Content-Type","application/json")); httpRequest.addHeader(new HTTPHeader("Authorization", "key=" + API_KEY)); httpRequest.setPayload(jsonString.getBytes("UTF-8")); LOG.info("Sending POST request to: " + GCM_URL); response = URLFetchServiceFactory.getURLFetchService().fetch(httpRequest);
@Override public <T, R extends ApiResponse<T>> PendingResult<T> handlePost( String hostName, String url, String payload, String userAgent, Class<R> clazz, FieldNamingPolicy fieldNamingPolicy, long errorTimeout, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { FetchOptions fetchOptions = FetchOptions.Builder.withDeadline(10); HTTPRequest req = null; try { req = new HTTPRequest(new URL(hostName + url), HTTPMethod.POST, fetchOptions); req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=utf-8")); req.setPayload(payload.getBytes(UTF_8)); } catch (MalformedURLException e) { LOG.error("Request: {}{}", hostName, url, e); throw (new RuntimeException(e)); } return new GaePendingResult<>( req, client, clazz, fieldNamingPolicy, errorTimeout, maxRetries, exceptionsAllowedToRetry); }
private void addBody(HttpRequestImpl request, HTTPRequest fetchRequest, boolean createFormPostIfBodyIsEmpty) { byte[] data = null; try { Object body = request.getBody(); if (body == null && createFormPostIfBodyIsEmpty) { body = createFormPostBody(request); } if (isMultipart(request)) { HttpEntity multipart = prepareMultipart(request); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); multipart.writeTo(baos); data = baos.toByteArray(); fetchRequest.setHeader(new HTTPHeader(Header.ContentType, multipart.getContentType().getValue())); } else if (body != null) { InputStream is = convertOutgoing(body); data = Streams.readBytes(is); } } catch (Exception e) { throw new HttpException(e, "Failed to generate request body: %s", e.getMessage()); } if (data != null) { fetchRequest.setPayload(data); } }
@Override public LowLevelHttpResponse execute() throws IOException { // write content if (content != null) { String contentType = content.getType(); if (contentType != null) { addHeader("Content-Type", contentType); } String contentEncoding = content.getEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } ByteArrayOutputStream out = new ByteArrayOutputStream(); content.writeTo(out); byte[] payload = out.toByteArray(); if (payload.length != 0) { request.setPayload(payload); } } // connect URLFetchService service = URLFetchServiceFactory.getURLFetchService(); try { HTTPResponse response = service.fetch(request); return new UrlFetchResponse(response); } catch (ResponseTooLargeException e) { IOException ioException = new IOException(); ioException.initCause(e); throw ioException; } }
@VisibleForTesting HTTPRequest makeRequest(GcsFilename filename, @Nullable Map<String, String> queryStrings, HTTPMethod method, long timeoutMillis, byte[] payload) { HTTPRequest request = new HTTPRequest(makeUrl(filename, queryStrings), method, FetchOptions.Builder.disallowTruncate() .doNotFollowRedirects() .validateCertificate() .setDeadline(timeoutMillis / 1000.0)); for (HTTPHeader header : headers) { request.addHeader(header); } request.addHeader(USER_AGENT); if (payload != null && payload.length > 0) { request.setHeader(new HTTPHeader(CONTENT_LENGTH, String.valueOf(payload.length))); try { request.setHeader(new HTTPHeader(CONTENT_MD5, BaseEncoding.base64().encode(MessageDigest.getInstance("MD5").digest(payload)))); } catch (NoSuchAlgorithmException e) { log.severe( "Unable to get a MessageDigest instance, no Content-MD5 header sent.\n" + e.toString()); } request.setPayload(payload); } else { request.setHeader(ZERO_CONTENT_LENGTH); } return request; }
static HTTPRequest copyRequest(HTTPRequest in) { HTTPRequest out = new HTTPRequest(in.getURL(), in.getMethod(), in.getFetchOptions()); for (HTTPHeader h : in.getHeaders()) { out.addHeader(h); } out.setPayload(in.getPayload()); return out; } }
static HTTPRequest createRequest(Request request) throws IOException { HTTPMethod httpMethod = getHttpMethod(request.getMethod()); URL url = new URL(request.getUrl()); HTTPRequest fetchRequest = new HTTPRequest(url, httpMethod); for (Header header : request.getHeaders()) { fetchRequest.addHeader(new HTTPHeader(header.getName(), header.getValue())); } TypedOutput body = request.getBody(); if (body != null) { String mimeType = body.mimeType(); if (mimeType != null) { fetchRequest.addHeader(new HTTPHeader("Content-Type", mimeType)); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); body.writeTo(baos); fetchRequest.setPayload(baos.toByteArray()); } return fetchRequest; }
@Override public LowLevelHttpResponse execute() throws IOException { // write content if (getStreamingContent() != null) { String contentType = getContentType(); if (contentType != null) { addHeader("Content-Type", contentType); } String contentEncoding = getContentEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } ByteArrayOutputStream out = new ByteArrayOutputStream(); getStreamingContent().writeTo(out); byte[] payload = out.toByteArray(); if (payload.length != 0) { request.setPayload(payload); } } // connect URLFetchService service = URLFetchServiceFactory.getURLFetchService(); HTTPResponse response = service.fetch(request); return new UrlFetchResponse(response); } }
@Test public void testPayload() throws Exception { URLFetchService service = URLFetchServiceFactory.getURLFetchService(); URL url = getFetchUrl(); HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST); req.setHeader(new HTTPHeader("Content-Type", "application/octet-stream")); req.setPayload("Tralala".getBytes(UTF_8)); HTTPResponse response = service.fetch(req); String content = new String(response.getContent()); Assert.assertEquals("Hopsasa", content); }
@Test public void testGetters() throws Exception { HTTPRequest request = new HTTPRequest(getFetchUrl(), HTTPMethod.PATCH, FetchOptions.Builder.withDefaults()); request.addHeader(new HTTPHeader("foo", "bar")); request.setPayload("qwerty".getBytes()); Assert.assertEquals(getFetchUrl(), request.getURL()); Assert.assertEquals(HTTPMethod.PATCH, request.getMethod()); Assert.assertNotNull(request.getFetchOptions()); Assert.assertNotNull(request.getHeaders()); Assert.assertEquals(1, request.getHeaders().size()); assertEquals(new HTTPHeader("foo", "bar"), request.getHeaders().get(0)); Assert.assertArrayEquals("qwerty".getBytes(), request.getPayload()); }
@Test public void testHeaders() throws Exception { URLFetchService service = URLFetchServiceFactory.getURLFetchService(); URL url = getFetchUrl(); HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST); req.setHeader(new HTTPHeader("Content-Type", "application/octet-stream")); req.setPayload("Headers!".getBytes(UTF_8)); HTTPResponse response = service.fetch(req); boolean found = false; List<HTTPHeader> headers = response.getHeadersUncombined(); for (HTTPHeader h : headers) { if (h.getName().equals("ABC")) { Assert.assertEquals("123", h.getValue()); found = true; break; } } Assert.assertTrue("Cannot find matching header <ABC : 123>: " + headers, found); found = false; headers = response.getHeaders(); for (HTTPHeader h : headers) { if (h.getName().equals("XYZ")) { Assert.assertEquals("1, 2, 3", h.getValue()); found = true; break; } } Assert.assertTrue("Cannot find matching header <XYZ : 1,2,3>: " + headers, found); }