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:com.github.zunix.ryoshi.api.resources.RootResourceTest.java
License:Open Source License
/** * State test with an authenticated User for * {@link com.github.zunix.ryoshi.api.resources.RootResource#getRoot} * * Expected Results from https://api.twitch.tv/kraken * @throws Exception// w w w.j a va2 s .c om */ @Test public void validateRootResponseAuthenticated() throws Exception { String expectedResultsURI = "https://api.twitch.tv/kraken"; Request request = new Request.Builder().url(expectedResultsURI) .header("Accept", "application/vnd.twitchtv.v3+json") .addHeader("Authorization", "OAuth " + accessToken).addHeader("Client-ID", clientID).build(); Response response = httpClient.newCall(request).execute(); String expectedResults = response.body().string(); RootResponse rootResponse = ryoshi.root().getRoot(); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String testRootResponseJson = gson.toJson(rootResponse); assertEquals("Fail - Root JSON don't match!", expectedResults, testRootResponseJson); }
From source file:com.google.android.gcm.demo.app.DemoActivity.java
License:Apache License
private boolean registerToPushd(String registrationId) throws IOException { String host = "http://vps.semoncat.com/push"; RequestBody formBody = new FormEncodingBuilder().add("proto", "gcm").add("token", registrationId) .add("lang", Locale.getDefault().toString()).add("timezone", TimeZone.getDefault().getID()).build(); String url = host + "/subscribers"; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(url).post(formBody).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { String id = new Gson().fromJson(response.body().string(), JsonObject.class).get("id").getAsString(); Log.d(TAG, "Id:" + id); //subscriber RequestBody subscriberFormBody = new FormEncodingBuilder().add("ignore_message", "0").build(); String subscriberUrl = host + "/subscriber/%s/subscriptions/zenui_help"; Request subscriberRequest = new Request.Builder() //.header("Authorization", getAuthHeader("SemonCat", "zoe80904")) .url(String.format(subscriberUrl, id)).post(subscriberFormBody).build(); Response subscriberResponse = client.newCall(subscriberRequest).execute(); return subscriberResponse.isSuccessful(); }//from www .j av a 2 s.c o m return false; }
From source file:com.google.example.gcmnetworkmanagerquickstart.MyTaskService.java
License:Open Source License
private int fetchUrl(OkHttpClient client, String url) { Request request = new Request.Builder().url(url).build(); try {/*from w ww . jav a2s .c o m*/ Response response = client.newCall(request).execute(); Log.d(TAG, "fetchUrl:response:" + response.body().string()); if (response.code() != 200) { return GcmNetworkManager.RESULT_FAILURE; } } catch (IOException e) { Log.e(TAG, "fetchUrl:error" + e.toString()); return GcmNetworkManager.RESULT_FAILURE; } return GcmNetworkManager.RESULT_SUCCESS; }
From source file:com.google.maps.internal.OkHttpPendingResult.java
License:Open Source License
private byte[] getBytes(Response response) throws IOException { InputStream in = response.body().byteStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int bytesRead; byte[] data = new byte[8192]; while ((bytesRead = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, bytesRead); }/*from w w w. ja v a 2 s . co m*/ buffer.flush(); return buffer.toByteArray(); }
From source file:com.google.minijoe.sys.Eval.java
License:Apache License
public void evalNative(int index, JsArray stack, int sp, int parCount) { switch (index) { case ID_HTTP_GET: try {/* w ww. ja va2s . c o m*/ String url = stack.getString(sp + 2); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_POST_JSON: try { OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), stack.getString(sp + 3)); Request request = new Request.Builder().url(stack.getString(sp + 2)).post(body).build(); Response response = client.newCall(request).execute(); stack.setObject(sp, response.body().string()); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CRAWLER: try { Crawler.startCrawler(stack.getString(sp + 2)); } catch (IOException ex) { ex.printStackTrace(); } break; case ID_CURL: new Thread(new Curl()).start(); break; case ID_EXTRACT_HTML: try { Readability readability = new Readability(new URL(stack.getString(sp + 2)), stack.getInt(sp + 3)); readability.init(); stack.setObject(sp, readability.outerHtml()); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } break; case ID_EVAL: try { stack.setObject(sp, eval(stack.getString(sp + 2), stack.isNull(sp + 3) ? stack.getJsObject(sp) : stack.getJsObject(sp + 3))); } catch (Exception e) { throw new RuntimeException("" + e); } break; case ID_COMPILE: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); Eval.compile(code, System.out); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOAD: try { File file = new File(stack.getString(sp + 2)); DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] data = new byte[(int) file.length()]; dis.readFully(data); String code = new String(data, "UTF-8"); //xxx.js Eval.eval(code, Eval.createGlobal()); dis.close(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_GEN_SITEMAP: try { // create web sitemap for web http://www.javavids.com WebSitemapGenerator webSitemapGenerator = new WebSitemapGenerator("http://www.javavids.com"); // add some URLs webSitemapGenerator.addPage(new WebPage().setName("index.php").setPriority(1.0) .setChangeFreq(ChangeFreq.NEVER).setLastMod(new Date())); webSitemapGenerator.addPage(new WebPage().setName("latest.php")); webSitemapGenerator.addPage(new WebPage().setName("contact.php")); // generate sitemap and save it to file /var/www/sitemap.xml File file = new File("/var/www/sitemap.xml"); webSitemapGenerator.constructAndSaveSitemap(file); // inform Google that this sitemap has changed webSitemapGenerator.pingGoogle(); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_WHOIS: try { stack.setObject(sp, Whois.getRawWhoisResults(stack.getString(sp + 2))); } catch (WhoisException e) { stack.setObject(sp, "Whois Exception " + e.getMessage()); } catch (HostNameValidationException e) { stack.setObject(sp, "Whois host name invalid " + e.getMessage()); } break; case ID_PAGERANK: stack.setObject(sp, PageRank.getPR(stack.getString(sp + 2))); break; case ID_SEND_TWITTER: try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Got request token."); System.out.println("Request token: " + requestToken.getToken()); System.out.println("Request token secret: " + requestToken.getTokenSecret()); AccessToken accessToken = null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out .print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } System.out.println("Got access token."); System.out.println("Access token: " + accessToken.getToken()); System.out.println("Access token secret: " + accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(stack.getString(sp + 2)); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } break; case ID_EXTRACT_TEXT: try { String url = stack.getString(sp + 2); String selector = stack.getString(sp + 3); Document doc = Jsoup.connect(url).userAgent("okhttp").timeout(5 * 1000).get(); HtmlToPlainText formatter = new HtmlToPlainText(); if (selector != null) { Elements elements = doc.select(selector); StringBuffer sb = new StringBuffer(); for (Element element : elements) { String plainText = formatter.getPlainText(element); sb.append(plainText); } stack.setObject(sp, sb.toString()); } else { stack.setObject(sp, formatter.getPlainText(doc)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LIST_LINKS: try { String url = stack.getString(sp + 2); print("Fetching %s...", url); Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); Elements media = doc.select("[src]"); Elements imports = doc.select("link[href]"); print("\nMedia: (%d)", media.size()); for (Element src : media) { if (src.tagName().equals("img")) print(" * %s: <%s> %sx%s (%s)", src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"), trim(src.attr("alt"), 20)); else print(" * %s: <%s>", src.tagName(), src.attr("abs:src")); } print("\nImports: (%d)", imports.size()); for (Element link : imports) { print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel")); } print("\nLinks: (%d)", links.size()); for (Element link : links) { print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35)); } } catch (Exception ex) { ex.printStackTrace(); } break; case ID_LOG: log.info(stack.getString(sp + 2)); break; case ID_SEND_MAIL: try { // put your e-mail address here final String yourAddress = "guilherme.@gmail.com"; // configure programatically your mail server info EmailTransportConfiguration.configure("smtp.server.com", true, false, "username", "password"); // and go! new EmailMessage().from("demo@guilhermechapiewski.com").to(yourAddress) .withSubject("Fluent Mail API").withAttachment("file_name").withBody("Demo message").send(); } catch (Exception ex) { stack.setObject(sp, "[ERROR]" + ex.getMessage()); } break; case ID_SNAPPY: try { String input = "Hello snappy-java! Snappy-java is a JNI-based wrapper of " + "Snappy, a fast compresser/decompresser."; byte[] compressed = Snappy.compress(input.getBytes("UTF-8")); byte[] uncompressed = Snappy.uncompress(compressed, 0, compressed.length); String result = new String(uncompressed, "UTF-8"); System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } break; case ID_OPENBROWSER: new Thread(new Runnable() { public void run() { openBrowser(); } }).start(); break; case ID_HELP: Enumeration ex = this.keys(); while (ex.hasMoreElements()) { String key = (String) ex.nextElement(); Object val = this.getRawInPrototypeChain(key); if (val instanceof JsFunction) { System.out.println(key + "---" + ((JsFunction) val).description); } else { System.out.println(key + "---" + val); } } break; default: super.evalNative(index, stack, sp, parCount); } }
From source file:com.google.sample.beaconservice.MainActivityFragment.java
License:Open Source License
private void insertIntoListAndFetchStatus(final Beacon beacon) { arrayAdapter.add(beacon);/*from w w w .java 2s.c o m*/ arrayAdapter.sort(RSSI_COMPARATOR); Callback getBeaconCallback = new Callback() { @Override public void onFailure(com.squareup.okhttp.Request request, IOException e) { Log.e(TAG, String.format("Failed request: %s, IOException %s", request, e)); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { Beacon fetchedBeacon; switch (response.code()) { case 200: try { String body = response.body().string(); Log.d(Constants.TEST_TAG, body); fetchedBeacon = new Beacon(new JSONObject(body)); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return; } break; case 403: fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.NOT_AUTHORIZED, beacon.rssi); break; case 404: fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.UNREGISTERED, beacon.rssi); break; default: Log.e(TAG, "Unhandled beacon service response: " + response); return; } int pos = arrayAdapter.getPosition(beacon); arrayList.set(pos, fetchedBeacon); updateArrayAdapter(); } }; client.getBeacon(getBeaconCallback, beacon.getBeaconName()); Log.d(Constants.TEST_TAG, "Beacon Name: " + beacon.getBeaconName()); }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_manage_beacon, container, false); advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type); advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id); status = (TextView) rootView.findViewById(R.id.status); placeId = (TextView) rootView.findViewById(R.id.placeId); placeId.setOnClickListener(new View.OnClickListener() { @Override/*w ww.j av a 2 s . com*/ public void onClick(View v) { editLatLngAction(); } }); latLng = (TextView) rootView.findViewById(R.id.latLng); latLng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); mapView = (ImageView) rootView.findViewById(R.id.mapView); mapView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editLatLngAction(); } }); expectedStability = (TextView) rootView.findViewById(R.id.expectedStability); expectedStability.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability"); final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.stability_enums, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); final Spinner spinner = new Spinner(getActivity()); spinner.setAdapter(adapter); // Set the position of the spinner to the current value. if (beacon.expectedStability != null && !beacon.expectedStability.equals(Beacon.STABILITY_UNSPECIFIED)) { for (int i = 0; i < spinner.getCount(); i++) { if (beacon.expectedStability.equals(spinner.getItemAtPosition(i))) { spinner.setSelection(i); } } } builder.setView(spinner); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beacon.expectedStability = (String) spinner.getSelectedItem(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); description = (TextView) rootView.findViewById(R.id.description); description.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description"); final EditText editText = new EditText(getActivity()); editText.setText(description.getText()); builder.setView(editText); builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { beacon.description = editText.getText().toString(); updateBeacon(); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } }); actionButton = (Button) rootView.findViewById(R.id.actionButton); decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton); decommissionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon") .setMessage("Are you sure you want to decommission this beacon? This operation is " + "irreversible and the beacon cannot be registered again") .setPositiveButton("Decommission", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Callback decommissionCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { beacon.status = Beacon.STATUS_DECOMMISSIONED; updateBeacon(); } else { String body = response.body().string(); logErrorAndToast("Unsuccessful decommissionBeacon request: " + body); } } }; client.decommissionBeacon(decommissionCallback, beacon.getBeaconName()); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }); attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider); attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel); attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout); // Fetch the namespace for the developer console project ID. We redraw the UI once that // request completes. // TODO: cache this. Callback listNamespacesCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); JSONArray namespaces = json.getJSONArray("namespaces"); // At present there can be only one namespace. String tmp = namespaces.getJSONObject(0).getString("namespaceName"); if (tmp.startsWith("namespaces/")) { namespace = tmp.substring("namespaces/".length()); } else { namespace = tmp; } Log.d(Constants.TEST_TAG, "Namespace " + namespace); redraw(); } catch (JSONException e) { Log.e(TAG, "JSONException", e); } } else { logErrorAndToast("Unsuccessful listNamespaces request: " + body); } } }; client.listNamespaces(listNamespacesCallback); return rootView; }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
private void updateBeacon() { // If the beacon hasn't been registered or was decommissioned, redraw the view and let the // commit happen in the parent action. if (beacon.status.equals(Beacon.UNREGISTERED) || beacon.status.equals(Beacon.STATUS_DECOMMISSIONED)) { redraw();//from ww w .j av a 2s . c o m return; } Callback updateBeaconCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { beacon = new Beacon(new JSONObject(body)); } catch (JSONException e) { logErrorAndToast("Failed JSON creation from response: " + body, e); return; } redraw(); } else { logErrorAndToast("Unsuccessful updateBeacon request: " + body); } } }; JSONObject json; try { json = beacon.toJson(); } catch (JSONException e) { logErrorAndToast("JSONException in creating update request", e); return; } client.updateBeacon(updateBeaconCallback, beacon.getBeaconName(), json); }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
private View.OnClickListener createActionButtonOnClickListener(final String status) { if (status == null) { return null; }//from w w w . jav a 2 s .co m if (!status.equals(Beacon.STATUS_ACTIVE) && !status.equals(Beacon.STATUS_INACTIVE) && !status.equals(Beacon.UNREGISTERED)) { return null; } return new View.OnClickListener() { @Override public void onClick(View v) { actionButton.setEnabled(false); Callback onClickCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(final Response response) throws IOException { String body = response.body().string(); if (response.isSuccessful()) { try { JSONObject json = new JSONObject(body); if (json.length() > 0) { // Activate, deactivate and decommission return empty responses. Register returns // a beacon object. beacon = new Beacon(json); } updateBeacon(); } catch (JSONException e) { logErrorAndToast("Failed JSON creation from response: " + body, e); } } else { logErrorAndToast("Unsuccessful request: " + body); } actionButton.setEnabled(true); } }; switch (status) { case Beacon.STATUS_ACTIVE: client.activateBeacon(onClickCallback, beacon.getBeaconName()); break; case Beacon.STATUS_INACTIVE: client.deactivateBeacon(onClickCallback, beacon.getBeaconName()); break; case Beacon.UNREGISTERED: try { JSONObject activeBeacon = beacon.toJson().put("status", Beacon.STATUS_ACTIVE); client.registerBeacon(onClickCallback, activeBeacon); } catch (JSONException e) { toast("JSONException: " + e); Log.e(TAG, "Failed to convert beacon to JSON", e); return; } break; } } }; }
From source file:com.google.sample.beaconservice.ManageBeaconFragment.java
License:Open Source License
private Button createAttachmentDeleteButton(final int viewId, final String attachmentName) { final Button button = new Button(getActivity()); button.setLayoutParams(BUTTON_COL_LAYOUT); button.setText("-"); button.setOnClickListener(new View.OnClickListener() { @Override/*from w w w .j a v a 2 s. c o m*/ public void onClick(View v) { Utils.setEnabledViews(false, button); Callback deleteAttachmentCallback = new Callback() { @Override public void onFailure(Request request, IOException e) { logErrorAndToast("Failed request: " + request, e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { attachmentsTable.removeView(attachmentsTable.findViewById(viewId)); } else { String body = response.body().string(); logErrorAndToast("Unsuccessful deleteAttachment request: " + body); } } }; client.deleteAttachment(deleteAttachmentCallback, attachmentName); } }); return button; }