I have a code that brings the json response from the twitter api. I want to use same code for facebook graph api to get json response from the Facebook but facebook doesn't provide any consumer keys as twitter. I can change this code to get the facebook json response. Can any of you help to modify the code.
public class TwitterResponse {
static String AccessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String AccessSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
/**
* #param args
*/
public static void main(String[] args) throws Exception
{
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(ConsumerKey,ConsumerSecret);
String twitterUrl="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=heymailme143&count=1&include_rts=true&contributors=true";
consumer.setTokenWithSecret(AccessToken, AccessSecret);
//HttpGet request = new HttpGet("https://api.twitter.com/1.1/friends/list.json");
HttpGet request = new HttpGet(twitter);
consumer.sign(request);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String m=IOUtils.toString(response.getEntity().getContent());
System.out.println(m);
System.out.println(statusCode + ":" + response.getStatusLine().getReasonPhrase());
}
}
This is a sample code I used to get the twitter response. Could you help me in changing it to get the facebook response using fb graph api?
Have a look at
http://facebook4j.org/en/index.html
which also has some examples.
I'm Looking for this :)
public String getUserInfo(String access_token) throws MalformedURLException, ProtocolException, IOException {
try {
String connection = connectionGet("https://graph.facebook.com/me?access_token=" + access_token, "");
System.out.println("done");
return connection;
} catch (Exception e) {
System.out.println("null value");
return null;
}
}
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
System.out.println(sb.toString());
return sb.toString();
}}
Related
public class AnalyticsDetectLanguage {
static String subscription_key_var;
static String subscription_key;
static String endpoint_var;
static String endpoint;
public static void Initialize () throws Exception {
subscription_key = "xxxxxx";
endpoint = "xxxxxxx";
}
static String path = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages";
public static String GetLanguage (Documents documents) throws Exception {
String text = new Gson().toJson(documents);
byte[] encoded_text = text.getBytes("UTF-8");
URL url = new URL(endpoint+path);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/json");
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscription_key);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(encoded_text, 0, encoded_text.length);
wr.flush();
wr.close();
StringBuilder response = new StringBuilder ();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(json_text).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main (String[] args) {
try {
Initialize();
Documents documents = new Documents ();
documents.add ("1", "This is a document written in English.");
documents.add ("2", "Este es un document escrito en Español.");
documents.add ("3", "这是一个用中文写的文件");
String response = GetLanguage (documents);
System.out.println (prettify (response));
}
catch (Exception e) {
System.out.println (e);
}
}
}
I am trying to work with the microsoft azure text analytics API but when I run this code with the correct keys I get a java.net.MalformedURLException on the endpoint key which itself is correct, but the error returns the key as xxxxxxxhttps. How do I get the code to run?
endpoint = "xxxxxxx";
URL url = new URL(endpoint+path);
The URL you end up with is "xxxxxxxhttps://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages".
Which is not a valid URL.
How to send sms using Twillio Api in Android.
Here is my code.
What I don't know is how to set http request body.
When I test it using CocoaRestClient(a tool for api test), it is working well.
Help me please.
public void sendInviteSMS(String kToNumber) {
int random4Num = generateRequestCode();
...
String kTwilioSID = "...";
String kTwilioSecret = "...";
String kFromNumber = "...";
String message = String.format("%s has sent you a invite. To accept, enter the following code: %d.", AppUtil.sharedObject().userFirstName, random4Num);
String kMessage = message;
String urlString = String.format("https://%s:%s#api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID);
HashMap postData = new HashMap();
postData.put("From", kFromNumber);
postData.put("To", kToNumber);
postData.put("Body", kMessage);
// Validate user with the POST call
AsyncTask doPost = new TwilioPost(urlString) {
#Override
protected void onPostExecute(String result) {
Log.v("PHONE", result);
}
}.execute(postData);
}
...
public class TwilioPost extends AsyncTask<HashMap<String, String>, Void, String> {
private String remoteURL;
private static final String TAG = "Wayjer";
public TwilioPost(String remoteURL) {
this.remoteURL = remoteURL;
}
////////////////////////////////////////////
// Call "doPost" in the background thread
///////////////////////////////////////////
#Override
protected String doInBackground(HashMap<String, String>... hashMaps) {
try {
return doPost(hashMaps[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
///////////////////////////////////////////////////////
// Override to convert result string to a JSONObject
//////////////////////////////////////////////////////
#Override
protected void onPostExecute(String result) {
try {
Log.v(TAG, result);
} catch (Exception e) {
Log.v(TAG, e.toString());
}
}
public String doPost(HashMap<String, String> postData) throws IOException {
URL url = new URL(remoteURL);
String response = "";
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
String postString = buildString(postData);
byte[] postBytes = postString.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
// Write parameter...
OutputStream outStream = connection.getOutputStream();
outStream.write(postBytes);
outStream.flush();
outStream.close();
connection.connect();
int resCode = connection.getResponseCode();
Log.v(TAG, "Response Message: " + connection.getResponseMessage());
if (resCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
response += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String buildString(HashMap<String, String> postData) throws UnsupportedEncodingException {
StringBuilder strBuilder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : postData.entrySet()) {
try {
Log.v(TAG, "HTTPPOST ENTRY: " + entry.getKey() + " - " + entry.getValue());
if (first)
first = false;
else
strBuilder.append("&");
strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
strBuilder.append("=");
strBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (Exception e) {
}
}
return strBuilder.toString();
}
}
Megan from Twilio here.
Interacting with the Twilio REST API directly from your mobile app is not recommended.
When sending SMS from Android, I would suggest that you have a server component using your language of choice. This allows you to keep your API credentials a secret.
Your mobile app would then connect to your server to make the request for sending SMS via the REST API with the parameters of the From, To and Body of the message:
https://www.twilio.com/docs/api/rest/sending-messages
In Java:
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
public class TwilioTest {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "YOUR_ACCOUNT_SID";
public static final String AUTH_TOKEN = "[AuthToken]";
public static void main(String[]args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "+16518675309"));
params.add(new BasicNameValuePair("From", "+14158141829"));
params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!"));
params.add(new BasicNameValuePair("MediaUrl", "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
Please let me know if this helps!
If you can otherwise provide an example error message you may be receiving with your code, I can take a closer look.
I am working on an app that makes an API call to a php script that echos a JSON Object. Testing the php file manually through a browser returns the expected information, but my app is acting as if the string that is returned is empty (before I even get to the point of decoding the JSON Object).
Here's the snippet of my code. I've used this script multiple times in my app successfully for api's that echo strings.
String urlParameters =
"request=item_search&item_num=" + barcode + "&ou=" + OU + "&user_tag=" + initials + "&version=" + version + "&scan_point=return";
URL url = null;
try {
if (testMode == true)
{
url = new URL("http://URL/api.php");
}
else
{
url = new URL("http://URL/api.php");
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
StringBuilder output = new StringBuilder();
try
{
assert url != null;
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
writer.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null)
{
output.append(line);
}
writer.close();
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String outputString = output.toString();
Have you tried OkHttp.
HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.
You can try following code:
package com.squareup.okhttp.guide;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
For more you can visit:
Vogella's article
OkHttp 2.0
Good day. Have just switched from objective-c to java and trying to read url contents normally to string. Read tons of posts and still it gives garbage.
public class TableMain {
/**
* #param args
*/
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
URL url = null;
URLConnection urlConn = null;
try {
url = new URL("http://svo.aero/timetable/today/");
} catch (MalformedURLException err) {
err.printStackTrace();
}
try {
urlConn = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
urlConn.getInputStream(), "UTF-8"));
StringBuilder strB = new StringBuilder();
String str;
while (null != (str = input.readLine())) {
strB.append(str).append("\r\n");
System.out.println(str);
}
input.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
What's wrong? I get something like this
??y??'??)j1???-?q?E?|V??,??< 9??d?Bw(?э?n?v?)i?x?????Z????q?MM3~??????G??љ??l?U3"Y?]????zxxDx????t^???5???j??k??u?q?j6?^t???????W??????????~?????????o6/?|?8??{???O????0?M>Z{srs??K???XV??4Z??'??n/??^??4????w+?????e???????[?{/??,??WO???????????.?.?x???????^?rax??]?xb??& ??8;?????}???h????H5????v?e?0?????-?????g?vN
Here is a method using HttpClient:
public HttpResponse getResponse(String url) throws IOException {
httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
return httpClient.execute(new HttpGet(url));
}
public String getSource(String url) throws IOException {
StringBuilder sb = new StringBuilder();
HttpResponse response = getResponse(url);
if (response.getEntity() == null) {
throw new IOException("Response entity not set");
}
BufferedReader contentReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = contentReader.readLine();
while ( line != null ){
sb.append(line)
.append(NEW_LINE);
line = contentReader.readLine();
}
return sb.toString();
}
Edit: I edited the response to ensure it uses utf-8.
This is a result of:
You are fetching data that is UTF-8 encoded
You are didn't specify, but I surmise you are printing it to the console on a Windows system
The data is being received and stored correctly, but when you print it the destination is incapable of rendering the Russian text. You will not be able to just "print" the text to stdout unless the ultimate display handler is capable of rendering the characters involved.
Is there any simplest way to parse JSON from a URL? I used Gson I can't find any helpful examples.
First you need to download the URL (as text):
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Then you need to parse it (and here you have some options).
GSON (full example):
static class Item {
String title;
String link;
String description;
}
static class Page {
String title;
String link;
String description;
String language;
List<Item> items;
}
public static void main(String[] args) throws Exception {
String json = readUrl("http://www.javascriptkit.com/"
+ "dhtmltutors/javascriptkit.json");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
System.out.println(page.title);
for (Item item : page.items)
System.out.println(" " + item.title);
}
Outputs:
javascriptkit.com
Document Text Resizer
JavaScript Reference- Keyboard/ Mouse Buttons Events
Dynamically loading an external JavaScript or CSS file
Try the java API from json.org:
try {
JSONObject json = new JSONObject(readUrl("..."));
String title = (String) json.get("title");
...
} catch (JSONException e) {
e.printStackTrace();
}
GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).
This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.
Only three lines of relevant code.
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;
import com.google.gson.Gson;
public class GsonFetchNetworkJson {
public static void main(String[] ignored) throws Exception {
URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
InputStreamReader reader = new InputStreamReader(url.openStream());
MyDto dto = new Gson().fromJson(reader, MyDto.class);
// using the deserialized object
System.out.println(dto.headers);
System.out.println(dto.args);
System.out.println(dto.origin);
System.out.println(dto.url);
}
private class MyDto {
Map<String, String> headers;
Map<String, String> args;
String origin;
String url;
}
}
If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.
You could use org.apache.commons.io.IOUtils for downloading and org.json.JSONTokener for parsing:
JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
System.out.println(jo.getString("version"));
Here is a easy method.
First parse the JSON from url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
Then place a task and then read the desired value from JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
You can then place a task like this -
new ReadPlacesFeedTask()
.execute("JSON URL");
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
I use java 1.8
with com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class can be also a complex type. Just for example used.
A simple alternative solution:
Paste the URL into a json to csv converter
Open the CSV file in either Excel or Open Office
Use the spreadsheet tools to parse the data