see the link using sample code
Sample Program
website get linkedin profile using java
You get the jar file signpost-core-1.1-SNAPSHOT.jar then save inside WEB-INF/lib
First create the website profile to LinkedIn.com
click the link --->https://www.linkedin.com/secure/developer
You get API key and security key
You put the key below the program 1
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import com.lowagie.text.pdf.codec.Base64;
public class Oauthprofile {
public static void main(String[] args) throws GeneralSecurityException, HttpException, IOException {
String baseUrl = "http://api.linkedin.com/v1/people/~";
String Consumer_key = "API Key";
//add one "&" after the access_token_secret;
String token_secret = "Security Key";// add your consumer secret(application secret) and access token secret
String token = "lookforshan@gmail.com";
long time = System.currentTimeMillis() / 1000;
String oauth_nonce = Md5(Long.toString(time));
String oauth_timestamp = Long.toString(time);
String base = "GET&" + URLEncoder.encode(baseUrl).replace("%7E", "~")+ "&";
String ParamerterString = "";
ParamerterString += "oauth_consumer_key="+Consumer_key+"&";
ParamerterString += "oauth_nonce="+oauth_nonce+"&";
ParamerterString += "oauth_signature_method=HMAC-SHA1&";
ParamerterString += "oauth_timestamp="+oauth_timestamp+"&";
ParamerterString += "oauth_token="+"lookforshan@gmail.com"+"&";
ParamerterString += "oauth_version=1.0";
base = base+ URLEncoder.encode(ParamerterString).replace("%7E", "~");
String signature = URLEncoder.encode(computeSignature(base,token_secret));
ParamerterString += "&oauth_signature="+signature;
String[] parameters = ParamerterString.split("&");
StringBuilder sb = new StringBuilder("OAuth realm=\"http://api.linkedin.com/\",");
for (int i = 0; i < authorization =" new" client =" new" getmethod =" new" hh =" getMethod.getRequestHeaders();" secretkey =" null;" keybytes =" keyString.getBytes();" secretkey =" new" mac =" Mac.getInstance(" text =" baseString.getBytes();" defaultbytes =" pass.getBytes();" algorithm =" MessageDigest.getInstance(" hexstring =" new" i="0;i"> 0 && isAuthenticationComplete();
}
public boolean isAuthenticationComplete() {
Object completeFlag = httpSession.getAttribute(AUTHENTICATION_COMPLETE_FLAG);
return null != completeFlag && completeFlag instanceof Boolean && ((Boolean) completeFlag).booleanValue();
}
public void setAuthenticationComplete(boolean isComplete) {
httpSession.setAttribute(AUTHENTICATION_COMPLETE_FLAG, new Boolean(isComplete));
}
public String getConsumerKey() {
return underlyingConsumer.getConsumerKey();
}
public String getConsumerSecret() {
return underlyingConsumer.getConsumerSecret();
}
public String getToken() {
return underlyingConsumer.getToken();
}
public String getTokenSecret() {
return underlyingConsumer.getTokenSecret();
}
public void setTokenWithSecret(String token, String secret) {
underlyingConsumer.setTokenWithSecret(token, secret);
// TBD: encrypt secret in the session?
if (token != null && secret != null) {
httpSession.setAttribute(TOKEN_KEY, token);
httpSession.setAttribute(TOKEN_SECRET_KEY, secret);
}
else {
httpSession.removeAttribute(TOKEN_KEY);
httpSession.removeAttribute(TOKEN_SECRET_KEY);
}
}
public HttpRequest sign(HttpRequest request)
throws OAuthMessageSignerException, OAuthExpectationFailedException {
return underlyingConsumer.sign(request);
}
public HttpRequest sign(Object obj) throws OAuthMessageSignerException,
OAuthExpectationFailedException {
return underlyingConsumer.sign(obj);
}
}
third Program 2
--------------------
package test;
import com.google.code.linkedinapi.schema.ApiStandardProfileRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import resume.bean.Register;
@SuppressWarnings("serial")
public class LinkedInAPIProxyServlet extends HttpServlet {
private String constructLinkedInAPIURL(String baseURL, HttpServletRequest request) {
//
// This constructs a LinkedIN API URL using the base URL and information from the path and request to this servlet
//
// Example:
// If this servlet is deployed to http://localhost:8080/api
// and a request is received at "http://localhost:8080/api/v1/people/~/connections?count=1"
// If this function is called with the baseURL is "http://api.linkedin.com"
// the resulting URL is "http://api.linkedin.com/v1/people/~/connections?count=1"
//
StringBuilder apiURL = new StringBuilder(baseURL);
String pathInfo = request.getPathInfo();
if (pathInfo != null && pathInfo.length() > 0) {
apiURL.append(pathInfo);
}
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
apiURL.append("?");
apiURL.append(queryString);
}
return apiURL.toString();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
OAuthSession authSession = LinkedInAuthentication.GetConsumer(req.getSession());
HttpSession session=req.getSession();
Register user=new Register();
user=(Register)session.getAttribute("userbean");
if (!authSession.isAuthenticated()) {
//
// redirect back to logon to re-authenticate, passing all of the parameters.
// These parameters will be passed back in once authentication succeeds.
//
String relativeLogonURL = constructLinkedInAPIURL("/logon", req);
URL reloginPage = new URL(new URL(req.getRequestURL().toString()), relativeLogonURL);
resp.sendRedirect(reloginPage.toString());
return;
}
String apiURL = constructLinkedInAPIURL("http://api.linkedin.com", req);
URL connectionsURL = new URL(apiURL);
HttpURLConnection apiRequest = (HttpURLConnection) connectionsURL.openConnection();
authSession.sign(apiRequest);
apiRequest.connect();
//
// Forward the API response
//
resp.setStatus(apiRequest.getResponseCode());
resp.setContentType(apiRequest.getContentType());
java.io.OutputStream out = resp.getOutputStream();
java.io.InputStream in = apiRequest.getInputStream();
byte[] data = new byte[4048];
int length = 0;
while ((length = in.read(data)) > 0) {
out.write(data, 0, length);
}
// resp.sendRedirect("http://localhost:8080/linkedInProfile.do");
//RequestDispatcher rd=req.getRequestDispatcher("/inde.jsp");
//rd.forward(req, resp);
in.close();
out.close();
}
catch (Throwable ex) {
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
the 3rd program get the linked in profile.
fourth program
----------------
package test;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
@SuppressWarnings("serial")
public class LogonServlet extends HttpServlet {
private static final String AUTH_TOKEN_PARAMETER = "oauth_token";
private static final String AUTH_TOKEN_VERIFIER_PARAMETER = "oauth_verifier";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
if (null != req.getParameter("logoff")) {
req.getSession().invalidate();
URL rootURL = new URL(new URL(req.getRequestURL().toString()), "/");
resp.sendRedirect(rootURL.toString());
return;
}
//
// The OAuthConsumer automatically stores the LinkedIn token and secret in the HTTP session
//
OAuthSession consumer = LinkedInAuthentication.GetConsumer(req.getSession());
OAuthProvider provider = LinkedInAuthentication.GetProvider(consumer);
String oauthToken = req.getParameter(AUTH_TOKEN_PARAMETER);
String oauthVerifier = req.getParameter(AUTH_TOKEN_VERIFIER_PARAMETER);
if (oauthToken != null && oauthVerifier != null) {
//
// This is the oauth callback - process the verifier to complete the authentication
//
// This writes the secret and token back to the consumer
//
provider.retrieveAccessToken(oauthVerifier);
consumer.setAuthenticationComplete(true);
StringBuilder relativeURL = new StringBuilder("/api");
String pathInfo = req.getPathInfo();
if (pathInfo != null) {
//
// Pass the requested LinkedIn API parameters to the "api" servlet
// if they were provided as part of logon. See the comments in LinkedInAPIProxyServlet.java
// for how the parameters are used.
//
relativeURL.append(pathInfo);
StringBuilder additionalParameters = new StringBuilder();
Enumeration parameterNames = req.getParameterNames();
boolean isFirstParameter = true;
while (parameterNames.hasMoreElements()) {
String parameterName = (String) parameterNames.nextElement();
if (!parameterName.equals(AUTH_TOKEN_PARAMETER) && !parameterName.equals(AUTH_TOKEN_VERIFIER_PARAMETER)) {
if (!isFirstParameter) {
additionalParameters.append("&");
}
additionalParameters.append(URLEncoder.encode(parameterName, "UTF-8"));
additionalParameters.append("=");
additionalParameters.append(URLEncoder.encode(req.getParameter(parameterName), "UTF-8"));
isFirstParameter = false;
}
}
if (additionalParameters.length() > 0) {
relativeURL.append("?");
relativeURL.append(additionalParameters.toString());
}
}
else {
//
// If no API parameters were requested, default to the current person's profile
//http://www.linkedin.com/connections?trk=hb_tab_cnts
///v1/people/~/connections?count=700
relativeURL.append("/v1/people/~/connections?count=1");
}
URL apiURL = new URL(new URL(req.getRequestURL().toString()), relativeURL.toString());
resp.sendRedirect(apiURL.toString());
}
else {
//
// This is the initial logon.
//
// The callback URL redirects to this servlet once authentication is complete.
//
StringBuffer requestURL = req.getRequestURL();
//
// embed any parameters passed in to logon. These will be used post-logon.
//
String queryString = req.getQueryString();
if (queryString != null && queryString.length() > 0) {
requestURL.append("?");
requestURL.append(queryString);
}
consumer.setAuthenticationComplete(false);
//
// Start the oauth process, redirecting to LinkedIn for authentication.
//
String authUrl = provider.retrieveRequestToken(requestURL.toString());
if(authUrl !=null){
// RequestDispatcher rd=req.getRequestDispatcher("/onlineprofile.jsp");
// rd.forward(req, resp);
}
resp.sendRedirect(authUrl);
}
}
catch (Throwable ex) {
// TODO
//resp.setContentType("text/plain");
//ex.printStackTrace(resp.getWriter());
}
}
}
web.xml
----------
Logon
test.LogonServlet
Logon
/logon/*
Logon
/logon
APIProxy
test.LinkedInAPIProxyServlet
APIProxy
/api/*
you give the url http://localhost:8080/logon
automatically redirect the linked login page . then you give the linkedin userid and password.
finally get the the profile (xml format)
No comments:
Post a Comment