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.
Related
I am trying to post some data into the server. I am using a sample url whichis available online. I am not able to proceed further because the line,
DataOutputStream os = new DataOutputStream(con.getOutputStream());, is throwing Connection Refused Exception.
This is the code...
public static void main(String[] args) throws Exception {
try {
URL url = new URL("https://my-json-server.typicode.com/typicode/demo/posts");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", 5);
DataOutputStream os = new DataOutputStream(con.getOutputStream());
os.writeBytes(jsonObj.toString());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
int responseCode = con.getResponseCode();
String output;
StringBuffer sb = new StringBuffer();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
sb.append(output);
break;
}
System.out.println("Response Code: "+responseCode);
System.out.println("URL: "+url);
System.out.println("Parameters: "+jsonObj.toString());
System.out.println("Output: "+output.toString());
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Below is the Exception..
java.net.ConnectException: Connection refused: 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.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at insertData.main(insertData.java:37)
Please help me with this. Thanks.
You need to change your BufferedReader to BufferedInputStream also the "while" loop that you have is constructed in a wrong way so far as i can see, follow the link in my previous comment
I am getting connection timeout: connect exception when I used username and password in url. url is "http://testadmin:testadmin#myhostName/manager/text/list";
This url working in chrome, firefox web browser but when i am going to access this url through java code.
Here is the output and exception I get:
&&&&&&&&&&&&&&&
*********88
response
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 java.net.Socket.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.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at test.TomcatTest.main(TomcatTest.java:23)
I'm using the following code.
package test;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class TomcatTest {
public static void main(String[] args) {
String listUrl = "http://testadmin:testadmin#myhostName/manager/text/list";
String serverResponse = "";
URL url = null;
try {
System.out.println("&&&&&&&&&&&&&&&");
url = new URL(listUrl);
URLConnection connection = url.openConnection();
System.out.println("*********88");
// i also tried without setting readtimeout.
connection.setReadTimeout(3 * 60 * 1000);// set timeout 3 minutes
InputStream inputStream = connection.getInputStream();
System.out.println("^^^^^^^^^^^^^");
int chr = -1;
while ((chr = inputStream.read()) != -1) {
System.out.print((char)chr);
serverResponse += (char)chr;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("response " + serverResponse);
}
}
The URL http://<user>:<pass>#url is not send in this way to the web server. The Browser takes username and password away from the url and creates a basic authentication header.
Java literally sends the URL to the server. Which is a security problem, because the URL might be logged at several stages.
This demo code is 99% based on answer by Wanderson Santos and joel234 with Java 8 Base64 adaptions:
String _url_string = "http://server/"
url = new URL(_url_string);
URLConnection uc = url.openConnection();
String userpass = _user + ":" + _password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
Now I've got a solution that we can not used username and password in url like as above.
It can be used like this:
String listUrl = "http://myHostName/manager/text/list";
//use username and password here
connection.setRequestProperty("Authorization", String.format("Basic %s", new BASE64Encoder().encode("testadmin:testadmin".getBytes("UTF-8"))));
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.
I am trying to get response from below REST api. when I open that URL in browser, I gets xml repsonse from server. but when I am trying to get the same using java program I am getting below exception
IOEXCeption
java.net.UnknownHostException: rxnav.nlm.nih.gov
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 java.net.Socket.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.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at com.test.demo.RestConnector.run(RestConnector.java:22)
at java.lang.Thread.run(Unknown Source)
Pls help me regarding this
below is the 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 RestConnector implements Runnable{
#Override
public void run() {
String URLString = "http://rxnav.nlm.nih.gov/REST/classes?src=MESH";
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if(connection.getResponseCode() != 200){
System.out.println("Failed to connect:"+connection.getResponseCode());
System.out.println("Response Message:"+connection.getResponseMessage());
}
System.out.println("I am here ");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line ;
while((line = reader.readLine()) != null){
System.out.println(line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOEXCeption");
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t = new Thread(new RestConnector());
t.start();
}
}
1) The error clearly says "can't resolve hostname".
2) Q: Does your AndroidManifest.xml grant Internet permissions? Make sure it contains this line:
<uses-permission android:name="android.permission.INTERNET" />
3) Q: is this a real device, or an emulator? If the latter, consider recreating your AVD. Believe it or not, that can sometimes help: Android java.net.UnknownHostException: Host is unresolved.
4) Finally, here are some other tips - including proxy server configuration - that might help:
http://eliasbland.wordpress.com/2011/02/22/java-net-unknownhostexception-on-android-a-list-of-possible-causes/
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