Can't fetch expanded URL from a given shortened URL - java

I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.

Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!

Related

Mailchimp Apache Error

im working with mailchimp, my objetive is to send users to the list in the mailchimp, so i used a wrapper from ecwid this one
So i did a method that send a test user to my list, i added my list id and my Api Key , but i have an error
this is my code
private void mailchimp(){
MailchimpClient client = new MailchimpClient("MY_API_KEY");
try {
EditMemberMethod.CreateOrUpdate method = new EditMemberMethod.CreateOrUpdate("MY_LIST_ID", "vasya.pupkin#gmail.com");
method.status = "subscribed";
method.merge_fields = new MailchimpObject();
method.merge_fields.mapping.put("FNAME", "Vasya");
method.merge_fields.mapping.put("LNAME", "Pupkin");
MemberInfo member = null;
Log.e("mailchimpmember",""+member);
member = client.execute(method);
} catch (IOException e) {
e.printStackTrace();
} catch (MailchimpException e) {
e.printStackTrace();
}
}
The problem is when i reach this method i get this from Apache in my android monitor at line MailchimpClient client = new MailchimpClient("MY_API_KEY");
No virtual method setConnectionManagerShared(Z)Lorg/apache/http/impl/client/HttpClientBuilder; in class Lorg/apache/http/impl/client/HttpClientBuilder; or its super classes (declaration of 'org.apache.http.impl.client.HttpClientBuilder' appears in /data/app/com.myapp.app.debug-1/split_lib_dependencies_apk.apk:classes78.dex)
at com.ecwid.maleorang.connector.HttpClientConnector.(HttpClientConnector.kt:71)
and this one
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/HttpClientBuilder;
im really struggling to get mailchimp running in my project, i cant find a good wrapper and dont know how to properly set it up
thanks
Check this video tutorial about posting new members to MailChimp list
https://www.youtube.com/watch?v=TkRUi_vN12k
Or just try using Volley for the http requests

Android URLEncoder.encode unhandled exception java.io.UnsupportedEncodingException

I try to implement Android searchable and I want to filter query, I follow this link, this, and others. but in Android Studio I got this message unhandled exception java.io.UnsupportedEncodingException, this is my code
import java.net.URLEncoder;`
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
searchRestaurants(URLEncoder.encode(queryStr, "UTF-8"));}
You need to wrap your URLEncoder.encode()-method in a try-catch block:
try {
URLEncoder.encode(queryStr, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Yourapp", "UnsupportedEncodingException");
}
The reason you're getting this error is that some platforms might not support UTF-8 encoding. Android definitely does, so you'll never receive this Exception, but you still need to handle it to make the compiler happy.
However, your code won't do anything, you'll need to store the result of the encode()-operation in a variable, e.g. String myEncodedQuery = URLEncoder.encode(queryStr, "UTF-8");.
import java.net.URLEncoder;
private void doSearch(String queryStr) {
// get a Cursor, prepare the ListAdapter
// and set it
//Log.e("Query",queryStr);
try {
final String encodedPath = URLEncoder.encode(queryStr, "UTF-8"));
searchRestaurants(encodedPath);
} catch (UnsupportedEncodingException ec) {
Log.d(TAG, ec.printStacktrace);
}
}

Mailjet API v3 update

I have a serious issue regarding the REST API of Mailjet as used with the recommended v3 library.
When I try to UPDATE I am able to do so for the first time without errors, but when I try to do so again, I got NullPointerException. In spite of that, it does update the stat in the Mailjet Server part.
Also the HTTP Response I get is HTTP/1.1 500 Internal Server Error
Code used:
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, **myUniqueID**).property(UserProperty.USERNAME, propertyValue).execute();
Any thoughts would be more than welcome.
Ok after the comment, here is the function:
#Path("/userUpdate/{propertyName}/{propertyValue}")
#GET
public Response userUpdate(#PathParam("propertyName") String propertyName, #PathParam("propertyValue") String propertyValue) throws ClientProtocolException, IOException{
MailJetApiClient cl=null;
User thisUser=null;
Response resp=null;
StringEntity stringEntity = null;
try {
cl = MailjetUsersRest.createClient();
} catch (MailJetClientConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
thisUser=cl.createCall(User.Get).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).execute();
} catch (MailJetApiCallException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try {
cl = MailjetUsersRest.createClient();
switch(propertyName){
case "Username":
thisUser=cl.createCall(User.Update).identifiedBy(UserProperty.ID, ___MY_UNIQUE_ID___).property(UserProperty.USERNAME, propertyValue).execute();
resp = Response.status(200).entity(thisUser).build();
break;
default:
System.out.println("Invalid propertyName.");
break;
}
} catch (MailJetClientConfigurationException | MailJetApiCallException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
First of all, thank you for using Mailjet!
After some testing, I was unable to reproduce your issue. You will find below the code I used.
However I strongly suggest that you open a ticket with our support here.
A working code
Please note that it is unnecessary and considered bad practice to rebuild the client before each call.
// Build a Mailjet client config
MailJetClientConfiguration config;
config = new MailJetClientConfiguration()
.setBaseUrl("https://api.mailjet.com/v3/REST/")
.setDefaultApiKey(System.getenv("MJ_PROD_PUBLIC"))
.setDefaultSecretKey(System.getenv("MJ_PROD_PRIVATE"));
// Build a Mailjet client
MailJetApiClient client = config.buildClient();
// Your code (adapted to my environment, ie no 'Response' object
// and no client factory.)
User thisUser = null;
try
{
// Note that the 'L' in the 'identifiedBy' value fi is necessary
thisUser = client
.createCall(User.Get)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.execute();
}
catch (MailJetApiCallException e2)
{
e2.printStackTrace();
}
String email = thisUser.getEmail();
String lastip = thisUser.getLastIp();
Date lastlogin = thisUser.getLastLoginAt();
String local = thisUser.getLocale();
String timezone = thisUser.getTimezone();
Date warned = thisUser.getWarnedRatelimitAt();
try
{
thisUser = client
.createCall(User.Update)
.identifiedBy(UserProperty.ID, /*Our user's ID*/L)
.property(UserProperty.USERNAME, "DevRel Team Mailjet")
.execute();
}
catch (MailJetApiCallException e)
{
e.printStackTrace();
}
Copy pasting the last bit (the update process) so that the update call is executed twice (without the same new username, of course) doesn't throw any error and certainly not a NullPointerException or a 500 HTTP error code.
And the username is changed accordingly.
So yeah, as written above, please contact our support here. This will allow us to better help you.
If this answer satisfies you, don't forget to accept & upvote it so that others going through similar issues can know this helped :-)

Writing a String to a webpage in Android

I'm trying to write a String to my webpage using Java in Android Studio by reusing some piece of codes of one Java Eclipse project which works well on my PC.
However, the String just cannot be written to the web page using my Android phone.
public void upload(String FTPaddress, String message){
try {
URL url = new URL(FTPaddress); // my server address
URLConnection urlc = url.openConnection();
OutputStream os = (OutputStream) urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
buffer.write(message.getBytes());
buffer.close();
os.close();
} catch (FileNotFoundException e) {
// print in log
} catch (IOException e) {
// print in log
}
}
Please note that the function is executed, the mobile phone is connected to the internet, thus I am running it on another thread using asyncTask, and there is no exceptions
So can anyone tell me why it worked on my laptop but not for my mobile phone?

Google Drive SDk Connection reset by peer

I am using following code to load public shared images from google drive to android app, but sometimes I got:
javax.net.ssl.SSLException: Read error: ssl=0x1d9ed0: I/O error during system call, Connection reset by peer
Why google drive is closing connection before I download image? This is happening randomly, but quite often. Does someone collide with such problem?
public static InputStream getStream(String url)
{
InputStream is = null;
try
{
is = new URL(url).openConnection().getInputStream();
} catch (MalformedURLException e)
{
L.e(e.toString());
} catch (IOException e)
{
L.e(e.toString());
}
return is;
}
For bitmap loading I use simple code:
BitmapFactory.decodeStream(stream, null, null);
It could be that you are affected by the following: The URL that you get from the file's metadata is short lived. If you are saving that URL to use later it won't work because it could be that the URL gets invalidated.
To do this you have to fetch the image metadata every time to get the new downloadURL.
We are working on providing non expirable URLs in the future.

Categories

Resources