So I am trying to get information of various images, for which I will use the Imgur API through Java.
I have found a library: https://github.com/fernandezpablo85/scribe-java,
but when trying the ImgUrTest.java # https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/ImgUrExample.java, I get the following stacktrace:
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'OAuth Verification Failed: The consumer_key "<Client-ID>" token "" combination does not exist or is not enabled.'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at ImgUrExample.main(ImgUrExample.java:31)
where <Client-ID> is my client id, as found on ImgUr's page.
I have checked that my Client Id and Client Secret are correct, I have tried making multiple apps on the ImgUr site, none of which work.
Edit: This code works:
URL imgURL = new URL(YOUR_REQUEST_URL);
HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection();
conn.setRequestMethod("GET");
if (accessToken != null) {
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
} else {
conn.setRequestProperty("Authorization", "Client-ID " + CLIENT_ID);
}
BufferedReader bin = null;
bin = new BufferedReader(new InputStreamReader(conn.getInputStream()));
First, the example is using Imgur API v2 which is old and unsupported. You should be using API v3.
Also note that:
For public read-only and anonymous resources, such as getting image
info, looking up user comments, etc. all you need to do is send an
authorization header with your client_id in your requests.
from docs at https://api.imgur.com/oauth2 -- so you don't really need OAuth for what you're doing.
There is some example Imgur API code that might help you, listed at https://api.imgur.com/ -- the Android example might be more relevant to you, since it uses Java, but unsurprisingly it comes with all the overhead of an Android project, compared with a plain Java application.
Related
I want to create QualityGates with the Web API in java.
String auth = username + ":" + password;
String authEncoded = Base64.getEncoder().encodeToString(auth.getBytes());
URL sonar = new URL("http://xxx.xxx.xxx.xx:9000/api/qualitygates/create");
HttpURLConnection conn = (HttpURLConnection) sonar.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authEncoded);
I dont seem to find anything in the topic of POST to web API.
In the Code i basically try to connect to the API with the Admin user authentication.
The Problem is, it doesnt matter what i do i always get ResponseCode 400. I know that it needs a name as a Property to create the QualityGate but that also doesnt seem to work.
My Question:
What do i need to do to use the POST method on web API's.
Best regards!
This isn't really a SonarQube question. It's a question about how to use POST apis. The API is returning a 400 error because you're not sending any data in the POST, and a POST expects data.
Read the answer to the following thread for hints on how to send data in a POST: Java - sending HTTP parameters via POST method easily .
I'm struggling to find good examples on how to POST key value pairs to a URL with Android in Java.
Here is what the Android documentation says (and pretty much every other example):
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
How do I implement writeStream?
Many other examples with POST put the parameters in the URL (a=1&b=2&c=3...), but then I could just use GET (?). And I don't want to place the parameters in the URL because that increases the chance of sensitive information to be logged on the server side.
Chrome POSTs data as such (body):
------WebKitFormBoundaryyr0AtYZxcOCCp7hA
Content-Disposition: form-data; name="parameterNameHere"
valueHere
------WebKitFormBoundaryyr0AtYZxcOCCp7hA--
Does the Android framework support this?
If not, are there any good libraries?
EDIT:
This is not a duplication of what was suggested. What was suggested does in no way answer the question, in that it does not show how to post with parameters, which is what this question is about.
There are many libraries out there that would help you achieve this. One of the libraries I use the most is OkHTTP. Include this library in your gradle and check the post from 'mauker' for an example on how to post
How to use OKHTTP to make a post request?
I am new to sharepoint rest API and am facing some issue while upload a file(image, document, pdf etc.,) to sharepoint online. Thanks in advance.
The below is our requirement.
User will upload the document which are stored at a particular location in application server.
A cron job will be running on application server and push the documents to share point online depend upon business needs.
To achieve it, we follow the below steps.
Authentication done via AZURE access token (We have used client credential flow to get access token from AZURE AD and able to communicate with sahrepoint online with access token.)
We have consumed the sharepoint online REST API to do file operation like upload, download etc,. using java code.
Here we are able to download the file from sharepoint online but when we upload the file, we are getting response as "BAD REQUEST" and status code is "400"
Sharepoint online rest API to create a file:
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)
method: POST
body: "Contents of file"
Headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
content-length:length of post body
My Java code :
//Create HttpURLConnection
String token ="js#1ikssj......RDS2" // This is just sample
String request = "Create a File with raw string !!!";
java.net.URL url = new java.net.URL("http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)");
java.net.URLConnection connection = url.openConnection();
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connection;
//Set Header
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Authorization", "Bearer " +token);
httpConn.setRequestProperty ("Accept", "application/json;odata=verbose");
httpConn.setRequestProperty("binaryStringRequestBody", "true");
//Send Request
java.io.DataOutputStream wr = new java.io.DataOutputStream(httpConn.getOutputStream ());
wr.writeBytes(request);
wr.flush();
wr.close();
//Read the response.
String StatusMessage = "HTTP ResponseCode: " + httpConn.getResponseCode() + " "+ httpConn.getResponseMessage();
Response : 400 - BAD REQUEST.
You can take a look of this project where you can find a working implementation of uploading files, creating folders, managing folder user permissions and more. It's a very easy to use API with most common operations of the rest API
https://github.com/kikovalle/PLGSharepointRestAPI-java
I'm trying to retrieve a github web page using a java code, for this I used following code.
String startingUrl = "https://github.com/xxxxxx";
URL url = new URL(startingUrl );
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.connect();
String line = null;
StringBuffer tmp = new StringBuffer();
try{
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
tmp.append(line);
}
}catch(FileNotFoundException e){
}
However, the page I received here is different from what I observe in browser after login to github. I tried sending authorization header as following, but it didn't worked either.
uc.setRequestProperty("Authorization", "Basic encodexxx");
How can I retrieve the same page that I see when I logged in?
I can't tell you more on this, because I don't know what are you getting, but most common issue for web crawlers is the fact that website owners mostly don't like web crawlers. Thus, you should behave like regular user - your browser for instance. Open your browser inspection element (press f12) when you are reaching some website and see what your browser send in request, then try to mimic it: For example, add Host, Referer, etc in your header. You need to experiment on this.
Also, good to know - some website owners will use advanced techniques (so they will block you to access their site), some won't stop you crawling on their website. Some will let you do what you want. Most fair option is to check www.somedomain.com/robots.txt and there is list of endpoints that are allowed for scraping and those that shouldn't be allowed.
Hello there I'm stuck on a oauth2 issue. I don't use spring. I have some JAX-RS web services made up using netbeans's included jersey jars. I have to secure this services using oauth 2 so that mobile client could use it without storing user credentials. I don't even know where to start as all examples I see use Spring... the ones that don't use spring use the Oltu library wich documentation doesn't convince me .Some oltu samples don't even work. Can anyone show me a tutorial that will help me build an authorization server from scratch using jersey and some library? any one even oltu ...
My answer will be based on Oltu. I'll be using CLIENT_CREDENTIALS authent.
Getting the token should look like this:
// We initialize a client
OAuthClient lOAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse lOAuthResponse;
// We are creating a request that's already formatted following the Oauth specs
OAuthClientRequest lRequest = OAuthClientRequest
.tokenLocation(TOKEN_SERVER_URI)
.setGrantType(GrantType.CLIENT_CREDENTIALS)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setScope("admin")
.buildBodyMessage();
//This will submit the request
String code = lOAuthClient.accessToken(lRequest, OAuthJSONAccessTokenResponse.class).getAccessToken();
System.out.println("Token obtained:" + token);
Now we can get our ressource using our token:
HttpURLConnection resourceConn = (HttpURLConnection) (new URL(RESSOURCE_SERVER_URI).openConnection());
resourceConn.addRequestProperty("Authorization", "Bearer " + token);
InputStream resource = resourceConn.getInputStream();
// Do whatever you want to do with the contents of resource at this point.
BufferedReader r = new BufferedReader(new InputStreamReader(resource, "UTF-8"));
String line = null;
while ((line = r.readLine()) != null)
System.out.println(line);