Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

From source file:alfio.plugin.mailchimp.MailChimpPlugin.java

License:Open Source License

private void createMergeField(String listAddress, String apiKey, String eventKey, int eventId) {

    Map<String, Object> mergeField = new HashMap<>();
    mergeField.put("tag", ALFIO_EVENT_KEY);
    mergeField.put("name", "Alfio's event key");
    mergeField.put("type", "text");
    mergeField.put("required", false);
    mergeField.put("public", false);

    Request request = new Request.Builder().url(listAddress + MERGE_FIELDS)
            .header("Authorization", Credentials.basic("alfio", apiKey)).post(RequestBody
                    .create(MediaType.parse(APPLICATION_JSON), Json.GSON.toJson(mergeField, Map.class)))
            .build();/*  w w  w. jav  a 2 s .  co  m*/

    try {
        Response response = httpClient.newCall(request).execute();
        if (!response.isSuccessful()) {
            log.debug("can't create {} merge field. Got: {}", ALFIO_EVENT_KEY, response.body().string());
        }
    } catch (IOException e) {
        pluginDataStorage.registerFailure(
                String.format("Cannot create merge field for %s, got: %s", eventKey, e.getMessage()), eventId);
        log.warn("exception while creating ALFIO_EKEY for event id " + eventId, e);
    }
}

From source file:apijson.demo.client.manager.HttpManager.java

License:Apache License

/**POST
 * @param url ?url//from w  w w  .  java  2  s  .  c o  m
 * @param request 
 * @param requestCode
 *            ?onActivityResult??activity?????
 *            {@link OnHttpResponseListener#onHttpResponse(int, String, Exception)}<br/>
 *            ??requestCode??
 * @param listener
 */
public void post(final String url_, final com.alibaba.fastjson.JSONObject request, final int requestCode,
        final OnHttpResponseListener listener) {
    if (request == null || request.containsKey(JSONRequest.KEY_TAG) == false) {
        throw new IllegalArgumentException("post  " + url_ + " \n"
                + "   request == null || request.containsKey(JSONRequest.KEY_TAG) == false !!!");
    }

    new AsyncTask<Void, Void, Exception>() {

        String result;

        @Override
        protected Exception doInBackground(Void... params) {

            try {
                String url = StringUtil.getNoBlankString(url_);

                OkHttpClient client = getHttpClient(url);
                if (client == null) {
                    return new Exception(TAG + ".post  AsyncTask.doInBackground  client == null >> return;");
                }
                String body = JSON.toJSONString(request);
                Log.d(TAG, "post  url_ = " + url_ + "\n request = \n" + body);

                RequestBody requestBody = RequestBody.create(TYPE_JSON, body);

                result = getResponseJson(client, new Request.Builder().addHeader(KEY_TOKEN, getToken(url))
                        .url(StringUtil.getNoBlankString(url)).post(requestBody).build());
            } catch (Exception e) {
                Log.e(TAG, "post  AsyncTask.doInBackground  try {  result = getResponseJson(..."
                        + "} catch (Exception e) {\n" + e.getMessage());
                return e;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Exception exception) {
            super.onPostExecute(exception);
            listener.onHttpResponse(requestCode, result, exception);
        }

    }.execute();
}

From source file:at.bitfire.dav4android.BasicDigestAuthenticatorTest.java

License:Open Source License

public void testMD5Sess() {
    BasicDigestAuthenticator authenticator = new BasicDigestAuthenticator(null, "admin", "12345",
            "hxk1lu63b6c7vhk");

    HttpUtils.AuthScheme authScheme = new HttpUtils.AuthScheme("Digest");
    authScheme.params.put("realm", "MD5-sess Example");
    authScheme.params.put("qop", "auth");
    authScheme.params.put("algorithm", "MD5-sess");
    authScheme.params.put("nonce", "dcd98b7102dd2f0e8b11d0f600bfb0c093");
    authScheme.params.put("opaque", "5ccc069c403ebaf9f0171e9517f40e41");

    /*  A1 = h("admin:MD5-sess Example:12345"):dcd98b7102dd2f0e8b11d0f600bfb0c093:hxk1lu63b6c7vhk =
          4eaed818bc587129e73b39c8d3e8425a:dcd98b7102dd2f0e8b11d0f600bfb0c093:hxk1lu63b6c7vhk       a994ee9d33e2f077d3a6e13e882f6686
    A2 = POST:/plain.txt                                                                            1b557703454e1aa1230c5523f54380ed
            /*from  w w  w  .j  a  va  2s. c  om*/
    h("a994ee9d33e2f077d3a6e13e882f6686:dcd98b7102dd2f0e8b11d0f600bfb0c093:00000001:hxk1lu63b6c7vhk:auth:1b557703454e1aa1230c5523f54380ed") =
    af2a72145775cfd08c36ad2676e89446
    */

    Request original = new Request.Builder()
            .method("POST", RequestBody.create(MediaType.parse("text/plain"), "PLAIN TEXT"))
            .url("http://example.com/plain.txt").build();
    Request request = authenticator.authorizationRequest(original, authScheme);
    String auth = request.header("Authorization");
    assertTrue(auth.contains("username=\"admin\""));
    assertTrue(auth.contains("realm=\"MD5-sess Example\""));
    assertTrue(auth.contains("nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\""));
    assertTrue(auth.contains("uri=\"/plain.txt\""));
    assertTrue(auth.contains("cnonce=\"hxk1lu63b6c7vhk\""));
    assertTrue(auth.contains("nc=00000001"));
    assertTrue(auth.contains("qop=auth"));
    assertTrue(auth.contains("response=\"af2a72145775cfd08c36ad2676e89446\""));
    assertTrue(auth.contains("opaque=\"5ccc069c403ebaf9f0171e9517f40e41\""));
}

From source file:at.bitfire.dav4android.BasicDigestAuthenticatorTest.java

License:Open Source License

public void testMD5AuthInt() {
    BasicDigestAuthenticator authenticator = new BasicDigestAuthenticator(null, "admin", "12435",
            "hxk1lu63b6c7vhk");

    HttpUtils.AuthScheme authScheme = new HttpUtils.AuthScheme("Digest");
    authScheme.params.put("realm", "AuthInt Example");
    authScheme.params.put("qop", "auth-int");
    authScheme.params.put("nonce", "367sj3265s5");
    authScheme.params.put("opaque", "87aaxcval4gba36");

    /*  A1 = admin:AuthInt Example:12345                            380dc3fc1305127cd2aa81ab68ef3f34
            //  w  w w. j a  va 2 s.com
    h("PLAIN TEXT") = 20296edbd4c4275fb416b64e4be752f9
    A2 = POST:/plain.txt:20296edbd4c4275fb416b64e4be752f9       a71c4c86e18b3993ffc98c6e426fe4b0
            
    h(380dc3fc1305127cd2aa81ab68ef3f34:367sj3265s5:00000001:hxk1lu63b6c7vhk:auth-int:a71c4c86e18b3993ffc98c6e426fe4b0) =
    81d07cb3b8d412b34144164124c970cb
    */

    Request original = new Request.Builder()
            .method("POST", RequestBody.create(MediaType.parse("text/plain"), "PLAIN TEXT"))
            .url("http://example.com/plain.txt").build();
    Request request = authenticator.authorizationRequest(original, authScheme);
    String auth = request.header("Authorization");
    assertTrue(auth.contains("username=\"admin\""));
    assertTrue(auth.contains("realm=\"AuthInt Example\""));
    assertTrue(auth.contains("nonce=\"367sj3265s5\""));
    assertTrue(auth.contains("uri=\"/plain.txt\""));
    assertTrue(auth.contains("cnonce=\"hxk1lu63b6c7vhk\""));
    assertTrue(auth.contains("nc=00000001"));
    assertTrue(auth.contains("qop=auth-int"));
    assertTrue(auth.contains("response=\"5ab6822b9d906cc711760a7783b28dca\""));
    assertTrue(auth.contains("opaque=\"87aaxcval4gba36\""));
}

From source file:at.bitfire.dav4android.DavAddressBook.java

License:Open Source License

public void addressbookQuery() throws IOException, HttpException, DavException {
    /* <!ELEMENT addressbook-query ((DAV:allprop |
                                 DAV:propname |
                                 DAV:prop)?, filter, limit?)>
       <!ELEMENT filter (prop-filter*)>
    *//*  w  w w  . j a  v  a 2 s. c  om*/
    XmlSerializer serializer = XmlUtils.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);
    serializer.startDocument("UTF-8", null);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.setPrefix("CARD", XmlUtils.NS_CARDDAV);
    serializer.startTag(XmlUtils.NS_CARDDAV, "addressbook-query");
    serializer.startTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_CARDDAV, "filter");
    serializer.endTag(XmlUtils.NS_CARDDAV, "filter");
    serializer.endTag(XmlUtils.NS_CARDDAV, "addressbook-query");
    serializer.endDocument();

    // redirects must not followed automatically (as it may rewrite REPORT requests to GET requests)
    httpClient.setFollowRedirects(false);

    Response response = httpClient.newCall(new Request.Builder().url(location)
            .method("REPORT", RequestBody.create(MIME_XML, writer.toString())).header("Depth", "1").build())
            .execute();

    checkStatus(response);
    assertMultiStatus(response);

    members.clear();
    processMultiStatus(response.body().charStream());
}

From source file:at.bitfire.dav4android.DavAddressBook.java

License:Open Source License

public void multiget(HttpUrl[] urls, boolean vCard4) throws IOException, HttpException, DavException {
    /* <!ELEMENT addressbook-multiget ((DAV:allprop |
                                    DAV:propname |
                                    DAV:prop)?,
                                    DAV:href+)>
    *///from  w  w w .  j  ava  2 s  .  c  o m
    XmlSerializer serializer = XmlUtils.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);
    serializer.startDocument("UTF-8", null);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.setPrefix("CARD", XmlUtils.NS_CARDDAV);
    serializer.startTag(XmlUtils.NS_CARDDAV, "addressbook-multiget");
    serializer.startTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getcontenttype"); // to determine the character set
    serializer.endTag(XmlUtils.NS_WEBDAV, "getcontenttype");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.startTag(XmlUtils.NS_CARDDAV, "address-data");
    if (vCard4) {
        serializer.attribute(null, "content-type", "text/vcard");
        serializer.attribute(null, "version", "4.0");
    }
    serializer.endTag(XmlUtils.NS_CARDDAV, "address-data");
    serializer.endTag(XmlUtils.NS_WEBDAV, "prop");
    for (HttpUrl url : urls) {
        serializer.startTag(XmlUtils.NS_WEBDAV, "href");
        serializer.text(url.encodedPath());
        serializer.endTag(XmlUtils.NS_WEBDAV, "href");
    }
    serializer.endTag(XmlUtils.NS_CARDDAV, "addressbook-multiget");
    serializer.endDocument();

    // redirects must not followed automatically (as it may rewrite REPORT requests to GET requests)
    httpClient.setFollowRedirects(false);

    Response response = httpClient.newCall(new Request.Builder().url(location)
            .method("REPORT", RequestBody.create(MIME_XML, writer.toString())).header("Depth", "0") // "The request MUST include a Depth: 0 header [...]"
            .build()).execute();

    checkStatus(response);
    assertMultiStatus(response);

    members.clear();
    processMultiStatus(response.body().charStream());
}

From source file:at.bitfire.dav4android.DavCalendar.java

License:Open Source License

public void calendarQuery(String component) throws IOException, HttpException, DavException {
    /* <!ELEMENT calendar-query ((DAV:allprop |
                              DAV:propname |
                              DAV:prop)?, filter, timezone?)>
       <!ELEMENT filter (comp-filter)>
       <!ELEMENT comp-filter (is-not-defined | (time-range?,
                          prop-filter*, comp-filter*))>
       <!ATTLIST comp-filter name CDATA #REQUIRED>
       name value: a calendar object or calendar component
               type (e.g., VEVENT)// w  w w .  j ava  2 s .c  om
            
    */
    XmlSerializer serializer = XmlUtils.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);
    serializer.startDocument("UTF-8", null);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.setPrefix("CAL", XmlUtils.NS_CALDAV);
    serializer.startTag(XmlUtils.NS_CALDAV, "calendar-query");
    serializer.startTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_CALDAV, "filter");
    serializer.startTag(XmlUtils.NS_CALDAV, "comp-filter");
    serializer.attribute(null, "name", "VCALENDAR");
    serializer.startTag(XmlUtils.NS_CALDAV, "comp-filter");
    serializer.attribute(null, "name", component);
    serializer.endTag(XmlUtils.NS_CALDAV, "comp-filter");
    serializer.endTag(XmlUtils.NS_CALDAV, "comp-filter");
    serializer.endTag(XmlUtils.NS_CALDAV, "filter");
    serializer.endTag(XmlUtils.NS_CALDAV, "calendar-query");
    serializer.endDocument();

    // redirects must not followed automatically (as it may rewrite REPORT requests to GET requests)
    httpClient.setFollowRedirects(false);

    Response response = httpClient.newCall(new Request.Builder().url(location)
            .method("REPORT", RequestBody.create(MIME_XML, writer.toString())).header("Depth", "1").build())
            .execute();

    checkStatus(response);
    assertMultiStatus(response);

    members.clear();
    processMultiStatus(response.body().charStream());
}

From source file:at.bitfire.dav4android.DavCalendar.java

License:Open Source License

public void multiget(HttpUrl[] urls) throws IOException, HttpException, DavException {
    /* <!ELEMENT calendar-multiget ((DAV:allprop |
                                DAV:propname |
                                DAV:prop)?, DAV:href+)>
    *//*from  w  ww  .  jav a  2 s  .co m*/
    XmlSerializer serializer = XmlUtils.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);
    serializer.startDocument("UTF-8", null);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.setPrefix("CAL", XmlUtils.NS_CALDAV);
    serializer.startTag(XmlUtils.NS_CALDAV, "calendar-multiget");
    serializer.startTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getcontenttype"); // to determine the character set
    serializer.endTag(XmlUtils.NS_WEBDAV, "getcontenttype");
    serializer.startTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.endTag(XmlUtils.NS_WEBDAV, "getetag");
    serializer.startTag(XmlUtils.NS_CALDAV, "calendar-data");
    serializer.endTag(XmlUtils.NS_CALDAV, "calendar-data");
    serializer.endTag(XmlUtils.NS_WEBDAV, "prop");
    for (HttpUrl url : urls) {
        serializer.startTag(XmlUtils.NS_WEBDAV, "href");
        serializer.text(url.encodedPath());
        serializer.endTag(XmlUtils.NS_WEBDAV, "href");
    }
    serializer.endTag(XmlUtils.NS_CALDAV, "calendar-multiget");
    serializer.endDocument();

    // redirects must not followed automatically (as it may rewrite REPORT requests to GET requests)
    httpClient.setFollowRedirects(false);

    Response response = httpClient.newCall(new Request.Builder().url(location)
            .method("REPORT", RequestBody.create(MIME_XML, writer.toString())).build()).execute();

    checkStatus(response);
    assertMultiStatus(response);

    members.clear();
    processMultiStatus(response.body().charStream());
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

/**
 * Sends a PROPFIND request to the resource. Expects and processes a 207 multi-status response.
 * #{@link #properties} are updated according to the multi-status response.
 * #{@link #members} is re-built according to the multi-status response (i.e. previous member entries won't be retained).
 * @param depth      "Depth" header to send, e.g. 0 or 1
 * @param reqProp    properties to request
 *///from w ww. ja  v a  2  s .c om
public void propfind(int depth, Property.Name... reqProp) throws IOException, HttpException, DavException {
    // build XML request body
    XmlSerializer serializer = XmlUtils.newSerializer();
    StringWriter writer = new StringWriter();
    serializer.setOutput(writer);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.setPrefix("CAL", XmlUtils.NS_CALDAV);
    serializer.setPrefix("CARD", XmlUtils.NS_CARDDAV);
    serializer.startDocument("UTF-8", null);
    serializer.setPrefix("", XmlUtils.NS_WEBDAV);
    serializer.startTag(XmlUtils.NS_WEBDAV, "propfind");
    serializer.startTag(XmlUtils.NS_WEBDAV, "prop");
    for (Property.Name prop : reqProp) {
        serializer.startTag(prop.namespace, prop.name);
        serializer.endTag(prop.namespace, prop.name);
    }
    serializer.endTag(XmlUtils.NS_WEBDAV, "prop");
    serializer.endTag(XmlUtils.NS_WEBDAV, "propfind");
    serializer.endDocument();

    // redirects must not followed automatically (as it may rewrite PROPFIND requests to GET requests)
    httpClient.setFollowRedirects(false);

    Response response = null;
    for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) {
        response = httpClient.newCall(new Request.Builder().url(location)
                .method("PROPFIND", RequestBody.create(MIME_XML, writer.toString()))
                .header("Depth", String.valueOf(depth)).build()).execute();
        if (response.isRedirect())
            processRedirection(response);
        else
            break;
    }

    checkStatus(response);
    assertMultiStatus(response);

    if (depth > 0)
        // collection listing requested, drop old member information
        members.clear();

    @Cleanup
    Reader reader = response.body().charStream();
    processMultiStatus(reader);
}

From source file:au.com.wallaceit.reddinator.RedditData.java

License:Open Source License

private String redditApiRequest(String urlStr, String method, int oauthMode, HashMap<String, String> formData)
        throws RedditApiException {
    String json;//from ww w . j av a  2  s  . com
    // create client if null
    if (httpClient == null) {
        createHttpClient();
    }
    try {
        Request.Builder httpRequest = new Request.Builder().url(urlStr);
        RequestBody httpRequestBody;
        String requestStr = "";
        if (formData != null) {
            FormEncodingBuilder formBuilder = new FormEncodingBuilder();
            Iterator iterator = formData.keySet().iterator();
            String key;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                formBuilder.add(key, formData.get(key));
            }
            httpRequestBody = formBuilder.build();
        } else {
            if (!method.equals("GET")) {
                int queryIndex = urlStr.indexOf("?");
                if (queryIndex != -1)
                    urlStr = urlStr.substring(queryIndex);
                requestStr = URLEncoder.encode(urlStr, "UTF-8");
            }
            httpRequestBody = RequestBody.create(POST_ENCODED, requestStr);
        }

        switch (method) {
        case "POST":
            httpRequest.post(httpRequestBody);
            break;
        case "PUT":
            httpRequest.put(httpRequestBody);
            break;
        case "DELETE":
            httpRequest.delete(httpRequestBody);
            break;
        case "GET":
        default:
            httpRequest.get();
            break;
        }
        if (oauthMode == REQUEST_MODE_OAUTHREQ) {
            // For oauth token retrieval and refresh
            httpRequest.addHeader("Authorization", "Basic " + Base64
                    .encodeToString((OAUTH_CLIENTID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        } else if (isLoggedIn() && oauthMode == REQUEST_MODE_AUTHED) {
            if (isTokenExpired()) {
                refreshToken();
            }
            // add auth headers
            String tokenStr = getTokenValue("token_type") + " " + getTokenValue("access_token");
            httpRequest.addHeader("Authorization", tokenStr);
        }

        Response response = httpClient.newCall(httpRequest.build()).execute();
        json = response.body().string();
        int errorCode = response.code();
        if (errorCode < 200 && errorCode > 202) {
            String errorMsg = getErrorText(json);
            throw new RedditApiException(
                    "Error " + String.valueOf(errorCode) + ": "
                            + (errorMsg.equals("") ? response.message() : errorMsg)
                            + (errorCode == 403 ? " (Authorization with Reddit required)" : ""),
                    errorCode == 403, errorCode);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RedditApiException("Error: " + e.getMessage());
    }

    return json;
}