i work with the linkedin-j lib and try to authorize, but there always an exception is thrown:
I try to authorize first. But if i fetch the
request
and the
authURL
an exception is thrown(see below).
This is my code:
private static String consumerKeyValue="[mykey]";
private static String consumerSecretValue="[mySecret]";
private static String accessTokenValue="[myTokenValue]";
private static String tokenSecretValue="[mytokenSecretValue]";
static LinkedInApiClientFactory factory;
static LinkedInApiClient client;
static LinkedInOAuthService oAuthService;
static LinkedInRequestToken request;
static String authURL;
private static LinkedInAccessToken accessToken;
public static void main(String[]args) throws IOException{
authorize(consumerKeyValue, tokenSecretValue);
createClient(consumerKeyValue, consumerSecretValue, accessTokenValue, tokenSecretValue);
}
public static void createClient(String key, String secret, String token, String secretToken){
factory=LinkedInApiClientFactory.newInstance(key,secret);
client=factory.createLinkedInApiClient(accessToken);
}
public static void authorize(String key, String secret) throws IOException{
oAuthService=LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(key, secret);
request=oAuthService.getOAuthRequestToken();
authURL=request.getAuthorizationUrl();
System.out.println("Paste this URL to your browser:");
System.out.println(authURL);
System.out.println("and now paste the given PIN here and press enter");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String input=br.readLine();
accessToken =oAuthService.getOAuthAccessToken(request, input);
}
}
and now following exception is thrown:
Exception in thread "main" com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:159)
at Connection.authorize(Connection.java:46)
at Connection.main(Connection.java:32)
Caused by: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:148)
... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
... 4 more
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
... 4 more
Related
I am trying to get the Json file at this link: https://api.imgflip.com/get_memes
When I add the link to the URL object in Java and try to connect using the HttpURLConnection object I keep on getting a 403 error. Could somebody help me out with the possible permission I might be missing?
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String url = "https://api.imgflip.com/get_memes";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
Error:
Sending 'GET' request to URL : https://api.imgflip.com/get_memesException in thread "main"
Response Code : 403
java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.imgflip.com/get_memes
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$10.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at Main.main(Main.java:25)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://api.imgflip.com/get_memes
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at Main.main(Main.java:20)
Their official website(https://api.imgflip.com/) says they have a rate limit on number of calls. You are probably exceeding number of calls.
The SoapUI webservices I'm having are client secured with .p12 and .cer formats.
When I hit the request from Eclipse, I'm getting the following console error.
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find
valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
Following is my code.
public class ClientService {
public static String webServiceURL = "URL";
public static String requestXMLPath = "Path for request xml";
public static String response="";
#Test
public void clientMethod() throws IOException, Throwable{
String methodname = Thread.currentThread().getStackTrace()[1].getMethodName();
String request = new String(Files.readAllBytes(Paths.get(requestXMLPath)));
PostMethod post = new PostMethod(webServiceURL);
HttpClient client = new HttpClient();
try{
post.setRequestHeader("Accept","application/soap+xml,application/dime,multipart/related,text/*");
RequestEntity requestEntity = new StringRequestEntity(request.toString(), "text/xml", "utf-8");
post.setRequestEntity(requestEntity);
client.executeMethod(post);
response = post.getResponseBodyAsString();
System.out.println(post.getStatusCode()+"\n"+post.getStatusLine()+"\n"+post.getStatusText());
String xmlformatresponse = response.replace("><", ">\n<");
System.out.println("Response is "+xmlformatresponse);
}
catch( Exception e){
System.out.println(e.getMessage());
}
}
}
As the webservice is client secured, I need to import the SSL certificate into Eclipse.
Could anyone provide the solution.
I am writing a file reader through REST api, simple code as below:
import domain
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
public class Verifier{
public static void main(String args[]) throws IOException
{
URL url = new URL("https://somehostname.xx.xxx.net/somecontent?somequery=number");
try{
HttpsURLConnection http=(HttpsURLConnection) url.openConnection();
int reponse = http.getResponseCode();
//some json processing
//...
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Then I got the error at line
int reponse = http.getResponseCode();
where the error message is:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching somehostname.xx.xxx.net found.
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at domain.main(Verifier.java:39)
Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching somehostname.xx.xxx.net found.
at sun.security.util.HostnameChecker.matchDNS(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 15 more
The content from the same site can be retrieved through the chrome browser, without any username or password (but it did show there is a problem with this website's security certificate in IE explorer, not in Chrome, you can continue to get the json content without typing anything).
I am thinking there might be some certificate problem in JAVA/eclipse, maybe? How can I solve it?
Thanks.
SSLContext sc = SSLContext.getInstance( "TLS");
TrustManager[] tmArr = {new X509TrustManager() {
#Override
public void checkClientTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
#Override
public void checkServerTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
sc.init(null, tmArr, new SecureRandom());
if (isDetail) {
if (!ValueWidget.isNullOrEmpty(tmArr)) {
System.out.println("first TrustManager:" + tmArr[0]);
}
}
huc = (HttpsURLConnection) url.openConnection();
//解决 javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative DNS name matching apis.map.qq.com found.
((HttpsURLConnection) huc).setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
public class SaveImageFromUrl {
public static void main(String[] args) throws Exception {
// proxy settings
System.setProperty("http.proxyHost", "porxyHost");
System.setProperty("http.proxyPort", "8080");
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("userxyz","password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
String destinationFile = "D://image4.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
My code works fine and downloads image for other imageurl paths.But it is not working when I use String imageUrl = "https://graph.facebook.com/10000012233xxxx/picture";
I am getting the following error :
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SaveImageFromUrl.saveImage(SaveImageFromUrl.java:33)
at SaveImageFromUrl.main(SaveImageFromUrl.java:28)
You need to make sure that your application can follow redirects, because Facebook is sending one if you request
/{user_id}/picture
To implement this, have a look at http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
Also, try setting the Proxy authentication like this:
System.setProperty( "http.proxyUserName", "username" );
System.setProperty( "http.proxyPassword", "password" );
I suspect you get the timeout from your proxy connection, but you should be able to test this yourself.
When using google api to translate the text I am getting the following error.
com.google.api.GoogleAPIException: java.lang.Exception: [google-api-translate-java] Error retrieving translation.
at com.google.api.translate.TranslateV2.execute(TranslateV2.java:68)
at GoogleTranslator.main(GoogleTranslator.java:16)
Caused by: java.lang.Exception: [google-api-translate-java] Error retrieving translation.
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:99)
at com.google.api.translate.TranslateV2.execute(TranslateV2.java:62)
... 1 more
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/language/translate/v2?key=AIzaSyAmtyPllqBCXu5rVikedZw8IErGCCfEdtw&q=How+are+you%3F&target=hi&source=en
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:93)
... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/language/translate/v2?key=AIzaSyAmtyPllqBCXu5rVikedZw8IErGCCfEdtw&q=How+are+you%3F&target=hi&source=en
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:89)
... 2 more
and my code is:
import com.google.api.GoogleAPI;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class GoogleTranslator {
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
// Translate.setHttpReferrer(“en-fr”);
GoogleAPI.setHttpReferrer("http://www.google.com");
GoogleAPI.setKey("my key");
String translatedText = Translate.DEFAULT.execute("How are you?",
Language.ENGLISH, Language.HINDI);
System.out.println(translatedText);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Please need your help in resolving this.