Find Facebook user (url to profile page) by known email address

后端 未结 11 1733
陌清茗
陌清茗 2020-12-01 03:40

I have an email address and want to find out if there is a Facebook user linked to this address. If there is, then I want to retrieve the url to this users profile page and

11条回答
  •  死守一世寂寞
    2020-12-01 04:23

    Andreas, I've also been looking for an "email-to-id" ellegant solution and couldn't find one. However, as you said, screen scraping is not such a bad idea in this case, because emails are unique and you either get a single match or none. As long as Facebook don't change their search page drastically, the following will do the trick:

    final static String USER_SEARCH_QUERY = "http://www.facebook.com/search.php?init=s:email&q=%s&type=users";
    final static String USER_URL_PREFIX = "http://www.facebook.com/profile.php?id=";
    
    public static String emailToID(String email)
    {
        try
        {
            String html = getHTML(String.format(USER_SEARCH_QUERY, email));
            if (html != null)
            {
                int i = html.indexOf(USER_URL_PREFIX) + USER_URL_PREFIX.length();
                if (i > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    char c;
                    while (Character.isDigit(c = html.charAt(i++)))
                        sb.append(c);
                    if (sb.length() > 0)
                        return sb.toString();
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    private static String getHTML(String htmlUrl) throws MalformedURLException, IOException
    {
        StringBuilder response = new StringBuilder();
        URL url = new URL(htmlUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");
        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            BufferedReader input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()), 8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null)
                response.append(strLine);
            input.close();
        }
        return (response.length() == 0) ? null : response.toString();
    }
    

提交回复
热议问题