Example usage for org.apache.http.client.entity EntityBuilder build

List of usage examples for org.apache.http.client.entity EntityBuilder build

Introduction

In this page you can find the example usage for org.apache.http.client.entity EntityBuilder build.

Prototype

public HttpEntity build() 

Source Link

Document

Creates new instance of HttpEntity based on the current state.

Usage

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String postDocument(String baseUrl, String receiverAddress, String externalId,
        UrkundSubmission submission, String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;/*from   w w  w.ja v  a2  s. c o m*/

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {

        HttpPost httppost = new HttpPost(baseUrl + "submissions/" + receiverAddress + "/" + externalId);
        //------------------------------------------------------------
        EntityBuilder eBuilder = EntityBuilder.create();
        eBuilder.setBinary(submission.getContent());

        httppost.setEntity(eBuilder.build());
        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httppost, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httppost.addHeader("Accept", "application/json");
        httppost.addHeader("Content-Type", submission.getMimeType());
        httppost.addHeader("Accept-Language", submission.getLanguage());
        httppost.addHeader("x-urkund-filename", submission.getFilenameEncoded());
        httppost.addHeader("x-urkund-submitter", submission.getSubmitterEmail());
        httppost.addHeader("x-urkund-anonymous", Boolean.toString(submission.isAnon()));
        httppost.addHeader("x-urkund-subject", submission.getSubject());
        httppost.addHeader("x-urkund-message", submission.getMessage());
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR uploading File : ", e);
    }

    return ret;
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Uploads the specified file to the community site. The return identifier
 * can be used later when composing other requests.
 * //from   w  w  w. j  ava 2s  .co m
 * @param httpclient
 *            the http client
 * @param attachment
 *            the file to attach
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the identifier of the file uploaded, <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie)
        throws CommunityAPIException {
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(attachment);
        byte fileContent[] = new byte[(int) attachment.length()];
        fin.read(fileContent);

        byte[] encodedFileContent = Base64.encodeBase64(fileContent);
        FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent);

        HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL);
        EntityBuilder fileUploadEntity = EntityBuilder.create();
        fileUploadEntity.setText(uploadReq.getAsJSON());
        fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        fileuploadPOST.setEntity(fileUploadEntity.build());

        CloseableHttpResponse resp = httpclient.execute(fileuploadPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$
            return fid;
        } else {
            CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }

    } catch (FileNotFoundException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Creates a new issue in the community tracker.
 * /*from   ww  w .j  a  v  a 2 s. c  o  m*/
 * @param httpclient
 *            the http client
 * @param newIssue
 *            the new issue to create on the community tracker
 * @param attachmentsIds
 *            the list of file identifiers that will be attached to the
 *            final issue
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the tracker URL of the newly created issue
 * @throws CommunityAPIException
 */
public static String createNewIssue(CloseableHttpClient httpclient, IssueRequest newIssue,
        List<String> attachmentsIds, Cookie authCookie) throws CommunityAPIException {
    try {
        // Add attachments if any
        if (!attachmentsIds.isEmpty()) {
            IssueField attachmentsField = new IssueField() {
                @Override
                protected String getValueAttributeName() {
                    return "fid"; //$NON-NLS-1$
                }

                @Override
                public boolean isArray() {
                    return true;
                }
            };
            attachmentsField.setName("field_bug_attachments"); //$NON-NLS-1$
            attachmentsField.setValues(attachmentsIds);
            newIssue.setAttachments(attachmentsField);
        }

        HttpPost issueCreationPOST = new HttpPost(CommunityConstants.ISSUE_CREATION_URL);
        EntityBuilder newIssueEntity = EntityBuilder.create();
        newIssueEntity.setText(newIssue.getAsJSON());
        newIssueEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        newIssueEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        issueCreationPOST.setEntity(newIssueEntity.build());
        HttpResponse httpResponse = httpclient.execute(issueCreationPOST);
        int httpRetCode = httpResponse.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(httpResponse.getEntity());

        if (HttpStatus.SC_OK != httpRetCode) {
            CommunityAPIException ex = new CommunityAPIException(
                    Messages.RESTCommunityHelper_IssueCreationError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        } else {
            // extract the node ID information in order
            // to retrieve the issue URL available on the tracker
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String nodeID = jsonRoot.get("nid").asText(); //$NON-NLS-1$
            JsonNode jsonNodeContent = retrieveNodeContentAsJSON(httpclient, nodeID, authCookie);
            return jsonNodeContent.get("path").asText(); //$NON-NLS-1$
        }

    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_IssueCreationError, e);
    }
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Executes the authentication to the Jaspersoft community in order to
 * retrieve the session cookie to use later for all other operations.
 * /*from   ww  w .ja va  2s.  c o m*/
 * @param httpclient
 *            the http client
 * 
 * @param cookieStore
 *            the Cookie Store instance
 * @param username
 *            the community user name (or email)
 * @param password
 *            the community user password
 * @return the authentication cookie if able to retrieve it,
 *         <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore,
        String username, String password) throws CommunityAPIException {

    try {
        HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL);
        EntityBuilder loginEntity = EntityBuilder.create();
        loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        loginPOST.setEntity(loginEntity.build());

        CloseableHttpResponse resp = httpclient.execute(loginPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());
        if (HttpStatus.SC_OK == httpRetCode) {
            // Can proceed
            List<Cookie> cookies = cookieStore.getCookies();
            Cookie authCookie = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$
                    authCookie = cookie;
                    break;
                }
            }
            return authCookie;
        } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) {
            // Unauthorized... wrong username or password
            CommunityAPIException unauthorizedEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_WrongUsernamePasswordError);
            unauthorizedEx.setHttpStatusCode(httpRetCode);
            unauthorizedEx.setResponseBodyAsString(responseBodyAsString);
            throw unauthorizedEx;
        } else {
            // Some other problem occurred
            CommunityAPIException generalEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_AuthInfoProblemsError);
            generalEx.setHttpStatusCode(httpRetCode);
            generalEx.setResponseBodyAsString(responseBodyAsString);
            throw generalEx;
        }
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

private HttpClient getMockClientWithResponse(byte[] respPayload, ContentType contentType, int status,
        boolean compressed) throws IOException {
    HttpClient mockClient = mock(HttpClient.class);
    HttpResponse mockResponse = mock(HttpResponse.class);

    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn("expected failure").when(mockStatusLine).getReasonPhrase();
    doReturn(status).when(mockStatusLine).getStatusCode();
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    EntityBuilder eb = EntityBuilder.create().setBinary(respPayload).setContentType(contentType);

    HttpEntity he;/*  w w w.  ja  v a  2s .  co  m*/
    if (compressed) {
        eb.setContentEncoding("gzip");
        he = new GzipDecompressingEntity(eb.build());
    } else {
        he = eb.build();
    }

    doReturn(he).when(mockResponse).getEntity();

    doReturn(mockResponse).when(mockClient).execute(any(HttpPost.class));
    return mockClient;
}

From source file:com.brienwheeler.svc.authorize_net.impl.CIMClientService.java

@Override
@MonitoredWork//from   ww  w  .  jav  a2s . c o m
@GracefulShutdown
@Transactional //(readOnly=true, propagation=Propagation.SUPPORTS)
public String getHostedProfilePageToken(DbId<User> userId, String returnUrl) {
    // More than two years later this still isn't in their Java SDK.  Oh well, let's just do it
    // the stupid way...

    String customerProfileId = userAttributeService.getAttribute(userId, ATTR_PROFILE_ID);
    if (customerProfileId == null)
        customerProfileId = createCustomerProfile(userId);

    StringBuffer buffer = new StringBuffer(4096);
    buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    buffer.append("<getHostedProfilePageRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n");
    buffer.append("  <merchantAuthentication>\n");
    buffer.append("    <name>" + apiLoginID + "</name>");
    buffer.append("    <transactionKey>" + transactionKey + "</transactionKey>\n");
    buffer.append("  </merchantAuthentication>\n");
    buffer.append("  <customerProfileId>" + customerProfileId + "</customerProfileId> \n");
    buffer.append("  <hostedProfileSettings>\n");
    buffer.append("    <setting>\n");
    buffer.append("      <settingName>hostedProfileReturnUrl</settingName>\n");
    buffer.append("      <settingValue>" + returnUrl + "</settingValue>\n");
    buffer.append("    </setting>\n");
    buffer.append("  </hostedProfileSettings>\n");
    buffer.append("</getHostedProfilePageRequest>\n");

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(merchant.isSandboxEnvironment() ? TEST_URL : PRODUCTION_URL);
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.TEXT_XML);
    entityBuilder.setContentEncoding("utf-8");
    entityBuilder.setText(buffer.toString());
    httpPost.setEntity(entityBuilder.build());

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String response = EntityUtils.toString(httpResponse.getEntity());
        int start = response.indexOf(ELEMENT_TOKEN_OPEN);
        if (start == -1)
            throw new AuthorizeNetException(
                    "error fetching hosted profile page token for " + userId + ", response: " + response);
        int end = response.indexOf(ELEMENT_TOKEN_CLOSE);
        if (end == -1)
            throw new AuthorizeNetException(
                    "error fetching hosted profile page token for " + userId + ", response: " + response);
        return response.substring(start + ELEMENT_TOKEN_OPEN.length(), end);

    } catch (ClientProtocolException e) {
        throw new AuthorizeNetException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AuthorizeNetException(e.getMessage(), e);
    }
}

From source file:org.identityconnectors.office365.Office365Connection.java

public boolean patchObject(String path, JSONObject body) {
    log.info("patchRequest(" + path + ")");

    // http://msdn.microsoft.com/en-us/library/windowsazure/dn151671.aspx
    HttpPatch httpPatch = new HttpPatch(getAPIEndPoint(path));
    httpPatch.addHeader("Authorization", this.getToken());
    // patch.addHeader("Content-Type", "application/json;odata=verbose");
    httpPatch.addHeader("DataServiceVersion", "3.0;NetFx");
    httpPatch.addHeader("MaxDataServiceVersion", "3.0;NetFx");
    httpPatch.addHeader("Accept", "application/atom+xml");

    EntityBuilder eb = EntityBuilder.create();
    eb.setText(body.toString());/*from   w  w  w .ja  v a 2  s  .co m*/
    eb.setContentType(ContentType.create("application/json"));
    httpPatch.setEntity(eb.build());

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {
        HttpResponse response = httpClient.execute(httpPatch);
        HttpEntity entity = response.getEntity();

        if (response.getStatusLine().getStatusCode() != 204) {
            log.error("An error occured when modify an object in Office 365");
            this.invalidateToken();
            StringBuffer sb = new StringBuffer();
            if (entity != null && entity.getContent() != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String s = null;

                log.info("Response :{0}", response.getStatusLine().toString());

                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    log.info(s);
                }
            }
            throw new ConnectorException("Modify Object failed to " + path + " and body of " + body.toString()
                    + ". Error code was " + response.getStatusLine().getStatusCode()
                    + ". Received the following response " + sb.toString());
        } else {
            return true;
        }
    } catch (ClientProtocolException cpe) {
        log.error(cpe, "Error doing patchRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing PATCH to " + path);
    } catch (IOException ioe) {
        log.error(ioe, "IOE Error doing patchRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing PATCH to " + path);
    }
}

From source file:org.identityconnectors.office365.Office365Connection.java

public Uid postRequest(String path, JSONObject body) {

    log.info("postRequest(" + path + ")");

    HttpPost post = new HttpPost(getAPIEndPoint(path));
    post.addHeader("Authorization", this.getToken());
    // patch.addHeader("Content-Type", "application/json;odata=verbose");
    post.addHeader("DataServiceVersion", "3.0;NetFx");
    post.addHeader("MaxDataServiceVersion", "3.0;NetFx");
    post.addHeader("Accept", "application/atom+xml");

    EntityBuilder eb = EntityBuilder.create();
    eb.setText(body.toString());/*from w  w w.  j  a v a2 s  .com*/
    eb.setContentType(ContentType.create("application/json"));
    post.setEntity(eb.build());

    HttpClient httpClient = HttpClientBuilder.create().build();

    try {
        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();

        log.info("Status code from postRequest is {0}", response.getStatusLine().getStatusCode());

        // assignLicense returns 200

        if ((response.getStatusLine().getStatusCode() != 201 && !path.contains("/assignLicense?"))
                || response.getStatusLine().getStatusCode() == 400) {
            log.error("An error occured when creating object in Office 365, path was {0}", path);
            this.invalidateToken();
            StringBuffer sb = new StringBuffer();
            if (entity != null && entity.getContent() != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String s = null;

                log.info("Response :{0}", response.getStatusLine().toString());

                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    log.info(s);
                }
            }
            throw new ConnectorException("Error on post to " + path + " and body of " + body.toString()
                    + ". Error code: " + response.getStatusLine().getStatusCode()
                    + " Received the following response " + sb.toString());
        } else if (path.contains("/assignLicense?") && response.getStatusLine().getStatusCode() == 200) {
            return SUCCESS_UID;
        } else {
            Header[] location = response.getHeaders("Location");
            // Location: https://directory.windows.net/contoso.onmicrosoft.com/directoryObjects/4e971521-101a-4311-94f4-0917d7218b4e/Microsoft.WindowsAzure.ActiveDirectory.User
            Matcher m = directoryObjectGUIDPattern.matcher(location[0].getValue());
            boolean b = m.matches();
            if (b) {
                String guid = m.group(1);
                log.info("Object has GUID of {0}", guid);
                return new Uid(guid);
            } else {
                log.error("No GUID found on path {0}", path);
                throw new ConnectorException("No GUID found for " + path + " and body of " + body.toString());
            }
        }
    } catch (ClientProtocolException cpe) {
        log.error(cpe, "Error doing postRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing POST to " + path);
    } catch (IOException ioe) {
        log.error(ioe, "IOE Error doing postRequest to path {0}", path);
        throw new ConnectorException("Exception whilst doing POST to " + path);
    }
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

@Override
public Response send(Request request, RequestOptions options) throws IOException {

    HttpUriRequest commonsRequest = null;

    switch (request.getMethod()) {
    case GET:/*from   w  ww  .  jav  a 2  s  .  c  om*/
        commonsRequest = new HttpGet(request.getURI());
        break;
    case DELETE:
        commonsRequest = new HttpDelete(request.getURI());
        break;
    case HEAD:
        commonsRequest = new HttpHead(request.getURI());
        break;
    case POST: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        } else {
            Collection<Parameter> parameters = request.getParameters();
            List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size());
            for (Parameter parameter : parameters) {
                String[] values = parameter.getValues();
                for (String value : values) {
                    nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value));
                }
            }
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    case PUT: {
        HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI());
        commonsRequest = entityEnclosingRequest;
        EntityBuilder entityBuilder = EntityBuilder.create();
        if (request.getBody() != null) {
            entityBuilder.setBinary(request.getBody().toByteArray());
        }
        entityEnclosingRequest.setEntity(entityBuilder.build());
        break;
    }
    }

    Collection<Header> headers = request.getHeaders();
    for (Header header : headers) {
        String[] values = header.getValues();
        for (String value : values) {
            commonsRequest.setHeader(header.getName(), value);
        }
    }

    ResponseBuilder builder = new ResponseBuilder();
    CloseableHttpResponse response = null;
    InputStream is = null;
    try {
        if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) {
            RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig)
                    .setRedirectsEnabled(options.followRedirects)
                    .setMaxRedirects(options.followRedirects ? 5 : 0).build();
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setRequestConfig(localConfig);
            response = httpClient.execute(commonsRequest, localContext);
        } else {
            response = httpClient.execute(commonsRequest);
        }

        builder.setStatusCode(response.getStatusLine().getStatusCode());
        for (org.apache.http.Header header : response.getAllHeaders()) {
            builder.addHeader(header.getName(), header.getValue());

        }
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            if (is != null) {
                builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes));
            }
        }

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                //TODO?
            }
        }
        if (response != null) {
            response.close();
        }
    }

    return builder.create();
}