Pages

Thursday, June 24, 2010

LinkedIn API

I have just started to work in this API with Java .bcoz am basically a Java developer.

Step-up LinkedIn API

To start your work with LinkedIn API, You need to get the
Consumer key \ API key & Consumer Secret \Secret Key.
Go for this link to get your Consumer key & Consumer Secret for your application
https://www.linkedin.com/secure/developer
You have to give application name & some regular fields you have to fill up.

IDE & JDK Version
Working with IBM Rational Application Developer-Version: 7.0.0
jdk used is 1.6 version.
You can work on Eclipse also.

Download 3 Jars

1.commons-codec-1.3.jar
http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/lib

2.linkedin-j.jar - http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/dist [version downloaded is May24]

3.signpost-core-1.2.1.1.jar - http://code.google.com/p/linkedin-j/source/browse/#svn/trunk/linkedin-j/lib

Included the jar in the class path and try to access the class in the jar

Got :( Error bcoz I tried out downloading snapshot version of linkedIn.jar ,
Not able to get the authService object.

final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);

Error got
Exception in thread "main" java.lang.NoClassDefFoundError: oauth/signpost/signature/OAuthMessageSigner
With the support of Linked Forum got rid from this issue.
http://developer.linkedin.com/message/5585#5585

Lets start coding ....
How to get LinkedIn –token, token secret & Authorization URL using consumer key & consumer secret?


final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);
LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken("your application url");
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
String authUrl = requestToken.getAuthorizationUrl();


Set all this objects in session.Inorder to proceed with the functions.

session.setAttribute("LINKEDIN_TOKEN", token);
session.setAttribute("LINKEDIN_TOKEN_SECRET", tokenSecret);
session.setAttribute("LINKEDIN_REQUEST_TOKEN", requestToken );
session.setAttribute("LINKEDIN_AUTH_URL", authUrl );

After execution of these codes, the service will be verfied .

Place this authorized url as a link in a jsp page.
When the link is clicked it asks for your LinkedIn username & Password.

How to get the LinkedIn –Access Token?

Once your application ,username& password are verified you will get a auth_verifier with the url.

String oauthVerifier = request.getParameter("oauth_verifier");
//Pass the requestToken[session.getAttribute("LINKEDIN_REQUEST_TOKEN")] & oauthVerifier to get accesstoken
LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(requestToken, oauthVerifier);

Set the access token in a session

session.setAttribute("LINKEDIN_ACCESS_TOKEN", accessToken);


How to create the Client Object?

Create the factory object by passing consumerKeyValue & consumerSecretValue

final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue);

Pass the access token to get the client object .

final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);


Functions in Linked-Id

Check out all the functions available in the LinedIn API

I have given some of the main functions with example code ,Here it goes...

To get the Current user Profile

Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID));
System.out.print("CurrentUsers Profile-Id >>"+profile.getId());

To get specific information of the Current User

Set the fields which you need .

Person userprofile = client.getProfileById(profile.getId(), EnumSet.of(ProfileField.FIRST_NAME,ProfileField.LAST_NAME,ProfileField.HEADLINE,ProfileField.INDUSTRY,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.PICTURE_URL, ProfileField.PUBLIC_PROFILE_URL));
System.out.println("PersonID:" + userprofile.getId());
System.out.println("Name:"+ userprofile.getFirstName()+ " " + userprofile.getLastName());
System.out.println("Headline:" + userprofile.getHeadline());
System.out.println("API Request:" + userprofile.getApiStandardProfileRequest());
System.out.println("Industry:" + userprofile.getIndustry());
System.out.println("Picture:" + userprofile.getPictureUrl());
System.out.println("Public URL:" + userprofile.getPublicProfileUrl());


To get the connections of the Current User
Set the fields which you need .

final Set connectionFields = EnumSet.of(ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE, ProfileField.INDUSTRY, ProfileField.CURRENT_STATUS, ProfileField.CURRENT_STATUS_TIMESTAMP,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.EDUCATIONS,ProfileField.PUBLIC_PROFILE_URL, ProfileField.POSITIONS, ProfileField.LOCATION, ProfileField.PICTURE_URL);

Pass the connection fields & get the connection object

Connections tryconnections = client.getConnectionsForCurrentUser(connectionFields);


Iterate the Person object from the person list.

for (Person person : connections.getPersonList()) {
System.out.println( "PersonId :"+ person.getId());
System.out.println("Name:" + person.getFirstName() + " " + person.getLastName());
System.out.println("Headline:" + person.getHeadline());
System.out.println("Industry:" + person.getIndustry());
System.out.println("Picture:" + person.getPictureUrl());

//To get the Location details

Location location = person.getLocation();
System.out.println("Location:" +location.getName()+" - "+location.getCountry().getCode());
System.out.println("API Request:" + person.getApiStandardProfileRequest());
System.out.println("Public URL:" + person.getPublicProfileUrl());

//To get the Header information

ApiStandardProfileRequest apiStandardProfileRequest=person.getApiStandardProfileRequest();
System.out.println("Header:" + apiStandardProfileRequest.getHeaders());
}


To get Profile ID by using public url

Pass the public URL of a person & connection fields

Person checkPerson = client.getProfileByUrl("public url of a person,connectionFields);
System.out.println("PersonID:" + checkPerson.getId());
System.out.println("Name:" + checkPerson.getFirstName() + " " + checkPerson.getLastName());
.
.

You can get all the data of a person for whatever fields mentioned in the connection field.

To get Profile ID by using Person ID

Pass the PersonID & required fields
Person othersProfile = client.getProfileById(userID, EnumSet.of(ProfileField.FIRST_NAME,ProfileField.LAST_NAME,ProfileField.HEADLINE,ProfileField.INDUSTRY,ProfileField.API_STANDARD_PROFILE_REQUEST, ProfileField.PICTURE_URL, ProfileField.PUBLIC_PROFILE_URL));

To invite by using E-mail
Pass the client object,emailId of the person you want to invite,firsname,lastname,subject & message.

inviteByEmailID(client,emailID, firstName, lastName,subject,msg);

Note:e-mail,first name & last name should not be passed Empty.Null Pointer Exception will be thrown.

To invite by using PersonId

Pass the header token value ,userId,subject & message.

Code to take the header token value

String tokenValue=authHeader.getHttpHeaderList().get(0).getValue();
System.out.println("tokenValue "+tokenValue);
client.sendInviteById("PersonID", subject, msg,tokenValue);


To send message to specific group of people

You have to pass the id’s of the people in a list whom you want to send message

Iterate the list in a for loop

client.sendMessage(Arrays.asList(((String) list.get(i)).split(",")), subj, message);

To Search within Linked In

We can search by passing company name,keyword,title,CountryCode
…etc

Example code is given for searching connection based on particular company

Function to put the search parameters [Company name is set]

private static Map getSearchParameters() {
Map searchParameters = new EnumMap(SearchParameter.class);
searchParameters.put(SearchParameter.COMPANY, "Kyyba");
return searchParameters;
}
Map SearchParameter, String searchParameters = getSearchParameters();


Pass the search Parameters to find the people based on search

People people = client.searchPeople(searchParameters);


To get the people information

for (Person person : people.getPersonList()) {
System.out.println(person.getId() + ":" + person.getFirstName() + " " + person.getLastName() + ":" + person.getHeadline());
}


We can't get the connections of connections

Connections otherscon = client.getConnectionsById("ProfielID");

Error will be thrown as Access to other member's connections denied.

In Linkedin forum they have mentioned as currently they not support getting other people's connections.

http://developer.linkedin.com/thread/1329
http://developer.linkedin.com/message/3706;jsessionid=3E26C276AF047188942CDE50F562B638.node0

9 comments:

  1. Hi this Blog is very helpful but i have a question how can we get the "Address" detail field present in the "Location" class since i am getting "name" field, but the address filed is null.

    ReplyDelete
  2. I was searching for this .....thanks to post this nice article



    GetTopLosers

    ReplyDelete
  3. How can I access the email Address...I have found that linkedin has updated its api, I tried doing

    Person person = client.profileForCurrentUser

    println person.emailAddress //output null

    I have given email permission too, r_emailaddress

    But still it prints email Address as null.

    Do you know a solution for it.

    Please Help!.


    ReplyDelete
  4. this method should be inside that class where doing stuff for oath
    public static Person getUser() {
    return client.getProfileForCurrentUser();
    }
    /////////////////

    Person p = LinkedInUtil.getUser();
    Sting firstname = p.getFirstName();
    String designation = p.getHeadline();

    String city = p.getLocation().getAddress().getCity();
    String state = p.getLocation().getAddress().getState();
    String street = p.getLocation().getAddress().getStreet1();
    String postalcode = p.getLocation().getAddress().getPostalCode();

    ReplyDelete
  5. How can we access emailaddress in android. I know email is accessbile as socialAuth library is giving email.

    ReplyDelete
  6. Hello shree
    I am using linked-in integration using custom-linkedin-j-android.jar for login and invitation by Id .
    It was working fine before the linked-in policy and Api modification but now it always showing below exception .
    Please give your suggestion for same.
    com.google.code.linkedinapi.client.LinkedInApiClientException: Access to sending invitation denied.

    Email-id--- idealittest@gmail.com

    ReplyDelete
  7. hi how to get the company pages the user is admin.

    ReplyDelete
  8. Succeed! It could be one of the most useful blogs we have ever come across on the subject. Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. Buy Linkedin Followers

    ReplyDelete
  9. Nice Article! I am so happy after reading your blog. It’s a very useful blog for us. Thanks for sharing your valuable information.
    visit site

    ReplyDelete