List of usage examples for com.squareup.okhttp Response body
ResponseBody body
To view the source code for com.squareup.okhttp Response body.
Click Source Link
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*)> *//*from w ww . j a va2 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("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+)> */// w w w . j a v a 2s . 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("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)/*from www . j a v a2 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("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 w w . jav a 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("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 GET request to the resource. Note that this method expects the server to * return an ETag (which is required for CalDAV and CardDAV, but not for WebDAV in general). * @param accept content of Accept header (must not be null, but may be */* ) * @return response body/*from w w w.j a v a 2s . c om*/ * @throws DavException on WebDAV errors, or when the response doesn't contain an ETag */ public ResponseBody get(@NonNull String accept) throws IOException, HttpException, DavException { Response response = null; for (int attempt = 0; attempt < MAX_REDIRECTS; attempt++) { response = httpClient .newCall(new Request.Builder().get().url(location).header("Accept", accept).build()).execute(); if (response.isRedirect()) processRedirection(response); else break; } checkStatus(response); String eTag = response.header("ETag"); if (TextUtils.isEmpty(eTag)) // CalDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc4791#section-5.3.4] // CardDAV servers MUST return ETag on GET [https://tools.ietf.org/html/rfc6352#section-6.3.2.3] throw new DavException("Received GET response without ETag"); properties.put(GetETag.NAME, new GetETag(eTag)); ResponseBody body = response.body(); if (body == null) throw new HttpException("GET without response body"); MediaType mimeType = body.contentType(); if (mimeType != null) properties.put(GetContentType.NAME, new GetContentType(mimeType)); return body; }
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 *//* 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:at.bitfire.dav4android.DavResource.java
License:Open Source License
protected void assertMultiStatus(Response response) throws DavException { if (response.code() != 207) throw new InvalidDavResponseException("Expected 207 Multi-Status"); if (response.body() == null) throw new InvalidDavResponseException("Received multi-status response without body"); MediaType mediaType = response.body().contentType(); if (mediaType != null) { if (!("application".equals(mediaType.type()) || "text".equals(mediaType.type())) || !"xml".equals(mediaType.subtype())) throw new InvalidDavResponseException("Received non-XML 207 Multi-Status"); } else//from www. j a v a 2 s.c o m log.warn("Received multi-status response without Content-Type, assuming XML"); }
From source file:at.bitfire.dav4android.exception.HttpException.java
License:Open Source License
public HttpException(Response response) { super(response.code() + " " + response.message()); status = response.code();/* w w w. j av a 2 s . c o m*/ message = response.message(); /* As we don't know the media type and character set of request and response body, only printable ASCII characters will be shown in clear text. Other octets will be shown as "[xx]" where xx is the hex value of the octet. */ // format request Request request = response.request(); StringBuilder formatted = new StringBuilder(); formatted.append(request.method() + " " + request.urlString() + "\n"); Headers headers = request.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (request.body() != null) try { formatted.append("\n"); Buffer buffer = new Buffer(); request.body().writeTo(buffer); while (!buffer.exhausted()) appendByte(formatted, buffer.readByte()); } catch (IOException e) { } this.request = formatted.toString(); // format response formatted = new StringBuilder(); formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n"); headers = response.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (response.body() != null) try { formatted.append("\n"); for (byte b : response.body().bytes()) appendByte(formatted, b); } catch (IOException e) { } this.response = formatted.toString(); }
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 w w w . java 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; }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Generate a new Device in Meshblu instance * * @param device model sample to create a new one. Basically this device model * contains attributes that will be saved into Meshblu. * Please note that uuid and token will always * be generated by Meshblu (please see AbstractThingDevice). * It is important set the custom attribute for your classes * @return New device with meshblu token and uuid values * @throws KnotException KnotException/*ww w. j a v a 2 s .com*/ * @see AbstractThingDevice */ public <T extends AbstractThingDevice> T createDevice(T device) throws KnotException { final String endPoint = mEndPoint + DEVICE_PATH; device.owner = abstractDeviceOwner.getUuid(); String json = mGson.toJson(device); RequestBody body = createRequestBodyWith(json); Request request = generateBasicRequestBuild(endPoint).post(body).build(); try { Response response = mHttpClient.newCall(request).execute(); // Retrieve the result of web service final T responseData = (T) mGson.fromJson(response.body().string(), device.getClass()); //Return the data sent by web server return responseData; } catch (Exception e) { throw new KnotException(e); } }