I'm following [this][1] documentation to connect to api, I want to build a JavaFX app that you can enter a word and it's retrieves it from api and I wanted to test the feature before displaying contents on GUI. Howerer I got this exception that the words is not found while I tested endpoint in their website and that word had definitions. I'm pretty new to using API perhaps I missed something that isn't shown in the documentation?
Here is my code:
public void testDetailsWords(String word,String detail) {
//String word = "lovely"; // Word
//String detail = "definitions"; // Detail
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
apiClient = Configuration.getDefaultApiClient();
apiClient.setBasePath("https://www.wordsapi.com/");
// configure authentications
Authentication auth;
auth = apiClient.getAuthentication("Default");
((ApiKeyAuth) auth).setApiKey(Apikey);
try {
WordsApi wordsApi = new WordsApi();
DetailsResponse response = wordsApi.details(word, detail);
System.out.println(response);
} catch (ApiException e) {
System.out.printf("ApiException caught: %s\n", e.getMessage());
}
}
Here is my Controller code :
#FXML
private void handleDefinitions(ActionEvent event) throws IOException {
String word =definitionsfield.getText();
String detail= "definitions";
apiCall.testDetailsWords(word,detail);
}
I would be grateful for the help.
[1]: http://restunited.com/docs/6vc24wq3ojpq
It's seems that tutorial that I tried following is very misleading which is very dissapoing, but I've learned my lesson now .
I decided to use Unirest to get request and it's worked perfectly.
If you stumble upon the link it's better not to follow that tutorial
Related
I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.
In my android application, I'm integrating the Dialogflow V2 Agent. There's no specific SDK for Android yet. So I'm using the java client library from Dialogflow. followed the tutorial https://github.com/dialogflow/dialogflow-java-client-v2/issues/25.
I've added the dependencies(dialogflow & oauth2) and created a service account in the google-cloud console. Added the credential file into raw folder. followed the tutorial here https://github.com/dialogflow/dialogflow-java-client-v2/issues/25. Getting the error as
java.lang.NoSuchMethodError: No static method
decodeBase64(Ljava/lang/String;)[B in class
Lorg/apache/commons/codec/binary/Base64; or its super classes
(declaration of 'org.apache.commons.codec.binary.Base64' appears in
/system/framework/org.apache.http.legacy.boot.jar)
private void createDialogflow() {
try {
InputStream stream = getResources().openRawResource(R.raw.dialogflow_service_credentials);
GoogleCredentials credentials = GoogleCredentials.fromStream(stream);
String projectId = ((ServiceAccountCredentials) credentials).getProjectId();
SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
sessionsClient = SessionsClient.create(sessionsSettings);
String uuid = UUID.randomUUID().toString();
session = SessionName.of(projectId, uuid);
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendMessage(String msg) {
// Java V2
setTypingMessage();
QueryInput queryInput = QueryInput.newBuilder().setText(TextInput.newBuilder().setText(msg).setLanguageCode("en-US")).build();
new RequestJavaV2Task(mContext, session, sessionsClient, queryInput).execute();
}
public void callbackV2(DetectIntentResponse response) {
removeTyingMessage();
if (response != null) {
// process aiResponse here
String botReply = response.getQueryResult().getFulfillmentText();
Log.d("botReply", "V2 Bot Reply: " + botReply);
setBotMessage(botReply);
} else {
Log.d("botReply", "Bot Reply: Null");
setBotMessage("There was some communication issue. Please Try again!");
}
}
Is there any clear documentations on how to integrate Dialogflow v2 into my android application.
The tutorial you were following was updated. In case anyone is facing this issue, according to the repo:
Save your CLIENT_ACCESS_TOKEN in gradle.properties
This code works fine for unrestricted sites. what are the changes to be done for restricted websites. Here is the restricted link.
http://www.manta.com/c/mrl70cq/geico
public class Scrape1 {
public static void main(String[] args) throws SQLException, IOException {
Document doc = null;
try {
doc = Jsoup.connect("http://www.manta.com/c/mrl70cq/geico").ignoreHttpErrors(true).get();
} catch (IOException e) {
e.printStackTrace();
}
String text = doc.html();
System.out.println(text);
}
}
Here is my error :
when i am running the above code with any URL it getting the whole data from the page. When i am using the following URL manta.com/c/mrl70cq/geico i am getting the following error: You're a power user moving through this website with super-human speed.You've disabled JavaScript in your web browser.A third-party browser plugin, such as Ghostery or NoScript, is preventing JavaScript from running
Any suggestions. Thanks in Advance.
I am facing problems in sharing media file using Gigya on Twitter. Please look below at the code snippet.
It is giving a error code as 0 but on the post, only text is getting posted.
private void share(){
GSObject userAction = new GSObject();
userAction.put("title", "Text");
GSArray mediaItems = new GSArray();
try {
mediaItems.add(new GSObject("{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}"));
userAction.put("mediaItems", mediaItems);
} catch (Exception e) {
e.printStackTrace();
}
GSObject params = new GSObject();
params.put("userAction", userAction);
params.put("enabledProviders", "twitter");
GSAPI.getInstance().sendRequest("socialize.publishUserAction", params, new GSResponseListener() {
#Override
public void onGSResponse(String method, GSResponse response, Object context) {
if (response.getErrorCode() == 0) {
Log.d( "Twitter Auth Token","Session token Response Error ");
} else {
Log.d( "Twitter Auth Token","Session token Response Error "+response);
}
}
}, null);
}
Gigya does not support uploading and sharing an image within a tweet. The recommended approach would be to include a link to the image within the tweet itself.
Hope this helps
EDIT
I don't think there is a solution for this issue.
Please look in Gigya documentation and examples:
1. Share.
2. Advance share.
Answer bellow is incorrect.
End EDIT
It seems that you may be missing the 'type' in the mediaItems object.
Please look in Gigya documentation.
The output user action json should look like this:
{
'title' : 'text',
'mediaItems' : [{
'type' : 'image',
'src' : 'http://www.f2h.co.il/logo.jpg',
}
],
}
At the moment, I am trying to create and update blog posts using the java sbt sdk api.
I could read blogs and blog posts and was able to retrieve a single blog post, using the .getBlogPost(bkogHandle, postId) method of the SDK.
But if I try to update or create a blog post, either I run into a NullPointerException or nothing happens.
For testing purposes I created a demo blog and tried to update the blog post inside it:
String blogHandle = "citb";
String postId = "7973d29e-26b6-4d23-ab04-ebfb734bf512";
BlogPost post = sbcs.getBlogService().getBlogPost(blogHandle, postId);
if (null != post){
System.out.println("Found post "+post.getTitle()+" ("+post.getAlternateUrl()+")");
Map<String, Object> fieldMap = post.getFieldsMap();
System.out.println("Found "+fieldMap.keySet().size()+" Entries in the field Map");
try{
//Save the post
System.out.println("Update blog post");
post.setContent("<p dir='ltr'>blabla "+new Date()+"</p>");
System.out.println(post.getContent());
post.setTitle(post.getTitle()+" +");
sbcs.getBlogService().updateBlogPost(post, blogHandle);
}catch(Exception e){
e.printStackTrace();
}
}
This example runs without throwing an exception but doesn't update the blog.
Do I miss something?
If I use post.save(blogHandle); I get the this error messages:
com.ibm.sbt.services.client.connections.blogs.BlogServiceException: error creating blog post
at com.ibm.sbt.services.client.connections.blogs.BlogService.createBlogPost(BlogService.java:627)
at com.ibm.sbt.services.client.connections.blogs.BlogPost.save(BlogPost.java:128)
Caused by: java.lang.NullPointerException
at com.ibm.sbt.services.client.connections.blogs.feedhandler.BlogsFeedHandler.createEntity(BlogsFeedHandler.java:42)
at com.ibm.sbt.services.client.connections.blogs.BlogService.createBlogPost(BlogService.java:624)
... 2 more
I get the same errors if I use createBlogPost(post, blogHandle)to create a new post.
Any ideas what the problem is or any suggestions what I could do to save blog posts?
EDIT:
In the BlogService class the problem seems to be in the following method
public BlogPost createBlogPost(BlogPost post, String blogHandle) throws BlogServiceException {
if (null == post){
throw new BlogServiceException(null,"null post");
}
Response result = null;
try {
BaseBlogTransformer transformer = new BaseBlogTransformer(post);
Object payload = transformer.transform(post.getFieldsMap());
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/atom+xml");
String createPostUrl = resolveUrl(blogHandle, FilterType.CREATE_BLOG_POST, null);
**result = createData(createPostUrl, null, headers, payload);**
**post = (BlogPost) new BlogPostsFeedHandler(this).createEntity(result);**
} catch (Exception e) {
throw new BlogServiceException(e, "error creating blog post");
}
return post;
}
I couldn't reproduce this issue but I fixed a bug on updateBlogPost just few days back , I don't think it is available in the mentioned build. So we'll have to check when the next build is due and we can confirm if the issue still comes.
for the save() in BlogPost -I'll make changes in it so as to return the updated BlogPost
You can fetch the exact cause for failure from service specific exception class, in this case BlogServiceException. BlogServiceException encapsulates all exceptions which might have been caused while communicating with Connections including Authentication and Authorization ones.
Another alternative for debugging and seeing all network calls would be redirect all traffic to debugging utility like fiddler, details for setting up SBT with fiddler can be fetched from this link SBT Wiki