The documentation on the Google API site does not include any complete working examples on using the groups api to access or modify a group, such as adding a member. There are snippets for different parts, but I am getting a 401 error when I put it all together and I have no idea if I am leaving out some key part.
I have tried putting the snippets I have found together into a working application, but am getting a 401 error.
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("<path to my json file I downloaded from the service accounts page>"))
.createScoped(Collections.singleton("https://www.googleapis.com/auth/admin.directory.group"));
URL url = new URL("https://www.googleapis.com/admin/directory/v1/groups/<identifier to the group, such as the group email address>/members");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
conn.setRequestProperty("Accept", "application/json");
StringBuffer jsonParamsBuffer = new StringBuffer();
jsonParamsBuffer .append("{")
.append("\"email\": \"")
.append("test-email#notarealdomain.fake")
.append("\", ")
.append("\"role\": \"")
.append("MEMBER")
.append("\"")
.append("}")
.append("]")
.append("}");
OutputStream os = conn.getOutputStream();
os.write(jsonParamsBuffer.toString().getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Response from Google Groups APi:");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
Server returned HTTP response code: 401 for URL: https://www.googleapis.com/admin/directory/v1/groups//members
Related
I am trying to call a web service using a java code which is throwing java.io.EOFException: Response had end of stream after 0 bytes for the large chunk of data.
The same web service call works in Postman REST Client, but Java code throws an error and it is not able to fetch web service response.
Can someone please help me with this?
Below is the code snippet for reference:
String output;
URL url = new URL(wsUrl); //wsUrl is a web service URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String authorization = "**************" + ":" + "*********";
String basicAuth = "Basic " + java.util
.Base64
.getEncoder()
.encodeToString(authorization.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Output from Server .... \n");
String jsonstring = new String();
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code).
My questions are:
Some of my web service just request header info, for example, I just need to
put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server?
try {
String input = jsonString;
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("errorcode" + conn.getResponseCode());
if (conn.getResponseCode() != 200) {
JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String jsonText = read(br);
System.out.println("jsonText: " + jsonText);
I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
I am using Java.Net.URL for making a Rest webservice call.
using the below example code.
URL url = new URL("UrlToConnect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
i am trying to capture response code from this webservice call. I observed that Even after putting a wrong URL i am getting 200 response code from the connection. Please suggest a way by which i can capture response codes 200 , 201 and 202.
Thanks.
I have written a Java Code to test the Watson Question and Answers API. However, I'm getting response code 500, when I run it. I have checked the api url and my login credentials. The problem seems to be somewhere else. Any hints or debugging suggestions would be of great help.
String url = "https://watson-wdc01.ihost.com/instance/526/deepqa/v1/question";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String userCredentials = "username:password";
String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty("X-SyncTimeout", "30");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestMethod("POST");
String query = "{\"question\": {\"questionText\": \"" + "What are the common respiratory diseases?" + "\"}}";
System.out.println(query);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
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());
When i open the same url with the browser I get this:
Watson Error!!
Error Encountered!!
Unable to communicate with Watson.
Whats wrong? Could it be something with the configuration? Or is the server down?
Any hints or debugging suggestions would be of great help.
Attempt the same request using your web browser ... or the curl utility.
Capture and output the contents of the error stream.
I don't think that this is the cause of your problems, but it is wrong anyway:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
You are writing to an API that expects text (JSON). You should therefore use a Writer, not a data (binary) output stream:
Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();