Is there any way to write text into an existing shared Google Document, or to create a new google file in a shared Google folder, using Java (and without connecting to any account, as documents and folders are shared) ?
Thanks !
*EDIT
Rather than using the Google API, I created a Google Form which is filled by the application and which is exported to a Google Sheet automatically. I'm able to do a "POST" Http request OR to open the pre-filled Google form :
try{URL url = new URL(my_google_form_direct_url);
//PREPARE PARAMS
Map<String,Object> params = new LinkedHashMap<>();
params.put("entry." + id_1, "TEXT1");
params.put("entry." + id_2, "TEXT2");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet()){
if(postData.length() != 0){postData.append('&');}
postData.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.name()));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), StandardCharsets.UTF_8.name()));}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8.name());
/************************************/
//SEND POST
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
//GET RESPONSE
int response = conn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8.name()));
InputStream in = conn.getInputStream();
in.close();}
conn.disconnect();
/************************************/
//OR OPEN THE PRE-FILLED FORM
URL prefilled_url = new URL(my_google_form_user_url + "?usp=pp_url&" + postData);
if(Desktop.isDesktopSupported()){
Desktop.getDesktop().browse(prefilled_url.toURI());}
}catch (IOException e1){e1.printStackTrace();}
But I was wondering if there is a limit for the length of the URL, when I open it with "Desktop" and when I do a POST request ?
Thanks!
you may use my pet project to submit Google forms through Java:
https://github.com/stepio/jgforms
Probably limits are mostly defined by HTTP standards, so this question may help you:
What is the maximum length of a URL in different browsers?
As per my experience with limits, I successfully used forms to implement a "logger" for Android app: got complete stack-traces logged along with explanatory messages.
Related
I want to get a query result from Stack Exchange API using my Java program. For example, I want to pass this URL and get the data of the question with id 805107. I have tried but only got the resulted web page content. I did not get the query result, i.e. the question data, although the resulted page shows the question data.
url = new URL ("https://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=805107&filter=default&site=stackoverflow&run=true");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput (true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
As Stephen C said, you need to use the query URL, not the URL of the documentation. You can find the query URL in the "Try it" part of the documentation page. Try using
url = new URL ("https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow")
It will return the result you are looking for as JSON like it is displayed on the documentation page.
I want to commit text file "demo2.txt" to bitbucket server using rest API. I can upload the same file using Postman but it's not working with Java code. As shown in the below code I want to send string object "str" as the body. Can someone help me here to upload the file on the bitbucket server? Also Please let me know if there is any other way to do this.
URL url = new URL("https://api.bitbucket.org/2.0/repositories/{team name}/{repository name}/src");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("X-Requested-with", "Curl");
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setRequestProperty("Connection", "Keep-Alive");
httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
httpCon.setRequestProperty("Accept", "application/x-www-form-urlencoded");
httpCon.setRequestProperty("Authorization", basicauth);
httpCon.setRequestMethod("POST");
String str =
"{"
+ "\"-F\":\"File3=#/D:/log/demo2.txt\" "
+ "}";
try {
OutputStream output = httpCon.getOutputStream();
output.write(str.getBytes());
output.close();
} catch(Exception e){
System.out.println(e.getMessage());
}
int responseCode = httpCon.getResponseCode();
String inputLine;
StringBuffer response = new StringBuffer();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED){
BufferedReader in = new BufferedReader(new .
InputStreamReader(httpCon.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
List<String> message = new ArrayList<>();
message.add(response.toString());
}
If this is all of your code, then your problem may be as simple as the fact that you're not making any sort of call to finalize the request...to tell HttpURLConnection that you're done forming the request and want it to complete. There are two things you can do to help this:
close the output stream when you're done writing to it. You're generally supposed to do this. Here, you can call output.close(). Better still, since you have a try/catch block already anyway, use a "try with resources" construct to make sure that the stream is closed no matter what happens (assuming you're using a newer version of Java that supports this).
make some sort of call to query the response to the request. It may
be that the request is not being fully sent until you do this. Try
calling httpCon.getResponseCode() at the bottom of your code.
Given that you have provided no information as to what "it's not working with Java code" means, this may be useful information but not the ultimate solution to your problem. Your code does look good other than exhibiting these omissions.
I'm trying to login to a portal. It works using Postman. When I try the same request using plain Java or OkHttp the login fails and I will be redirected to the login page.
HttpUrl.Builder httpBuilder = HttpUrl.parse("https://test58.cashctrl.com/auth/login.html").newBuilder();
httpBuilder.addQueryParameter("JMCF_AUTH_EMAIL", "email");
httpBuilder.addQueryParameter("JMCF_AUTH_PASSWORD", "password");
Request request = new Request.Builder()
.url(httpBuilder.build())
.get()
.build();
I know the Url looks weird but it works this way using Postman or even simply use a browser.
Alternative with plain Java, which I tried:
Map<String, String> parameters = new HashMap<>();
parameters.put(PARAM_EMAIL, EMAIL);
parameters.put(PARAM_PASSWORD, PASSWORD);
URL url = new URL(LOGIN_URL + "?" + ParameterStringBuilder.getParamsString(parameters));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine + "\n");
}
in.close();
con.disconnect();
System.out.println(status);
System.out.println(content.toString());
Postman must be doing something special or also a browser which I don't see.
I had the same issue, I got to know that Postman has "code" feature. Below the send button you can see the code option it will generate the code for you. There is a list of language to choose from and java is one of them. Do check that out. Also you must be missing the cookie, see the temporary headers in Postman add all in your code and do include the cookie one.
Thanks I hope it helps.
So there is this line of code
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(YOUR API KEY GOES HERE, "UTF-8");
and when I registered for the Imgur API I was given a client_id and a client_secret and was wondering which one I use for where it says "YOUR API KEY GOES HERE" also in the first part in the second line where it says "key" what do I enter there? Also is the site to upload it http://imgur.com/api/upload because I have seen a few different ones.
try this out:
public static String getImgurContent(String clientID) throws Exception {
URL url;
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(IMAGE_URL, "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
stb.append(line).append("\n");
}
wr.close();
rd.close();
return stb.toString();
}
was almost like humpty dumpty, getting every piece back together, codes from everywhere, at least it worked as expected, its a shame they don't have examples...
enjoy.
ps: ou can also make with FILES (haven't tried yet) but you need to convert an image to base64 and then to utf8 (to replace the url)
edit, use this instead of the URL, so you can upload files:
//create base64 image
BufferedImage image = null;
File file = new File(imageDir);
//read image
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = Base64.encode(byteImage);
String data = URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(dataImage, "UTF-8");
The site to upload to is - https://api.imgur.com/3/image or you can alternatively use the same link with "upload" instead of image.
I am currently trying to use the Imgur API myself and although I have not got it completely right yet (I can't seem to parse the URL response) I have looked at quite a few code examples for it. Are you definitely using version 3 of the API?
Because the homepage of the API says that you should give your client ID in this format "Authorization Client-ID YOUR_CLIENT_ID", not using "key" like you are.
Have a look at http://api.imgur.com/
Edit: you might find the following useful - Anonymous Uploading File object to Imgur API (JSON) gives Authentication Error 401
String album = "http://picasaweb.google.com/data/feed/api/user/"+email;
HttpURLConnection con = (HttpURLConnection) new URL(albumUrl).openConnection();
// request method, timeout and headers
con.setRequestMethod("GET") ;
con.setReadTimeout(15000);
con.setRequestProperty("Authorization", "GoogleLogin auth="+auth);
con.setRequestProperty("GData-Version", "2");
// set timeout and that we will process output
con.setReadTimeout(15000);
con.setDoOutput(true);
// connnect to url
con.connect();
// read output returned for url
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Problem : Everytime i call con.getInputStream() it gives me file not found exception.
But when i load the same url in the desktop browser then it is displaying correct data.
I am confused why on android it is throwing exception.
Thanks in advance.
Did you get this? Maybe you just missed the https
below example uses default for authenticated user and the experimental fields list.
url = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&access=public&fields="
+ URLEncoder
.encode("entry(title,id,gphoto:numphotosremaining,gphoto:numphotos,media:group/media:thumbnail)",
"UTF-8");
https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums