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();
Related
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
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();
I'm trying to send email using the SES HTTPS Query API. I have a java method that sends a GET request to an Amazon SES endpoint, I'm trying to send an email with SES and capture the result.
Code:
public static String SendElasticEmail(String timeConv,String action,String source, String destinationAddr, String subject, String body) {
try {
System.out.println("date : "+timeConv);
System.out.println("In Sending Mail Method......!!!!!");
//Construct the data
String data = "Action=" + URLEncoder.encode(action, "UTF-8");
data += "&Source=" + URLEncoder.encode(source, "UTF-8");
data += "&Destination.ToAddresses.member.1=" + URLEncoder.encode(destinationAddr, "UTF-8");
data += "&Message.Subject.Data=" + URLEncoder.encode(subject, "UTF-8");
data += "&Message.Body.Text.Data=" + URLEncoder.encode(body, "UTF-8");
//Send data
System.out.println("https://email.us-east-1.amazonaws.com?"+data);
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
//URLConnection conn = url.openConnection();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("x-amz-date" , timeConv);
con.setRequestProperty("Content-Length", ""+data.toString().length());
con.setRequestProperty("X-Amzn-Authorization" , authHeader);
int responseCode = ((HttpsURLConnection) con).getResponseCode();
String responseMessage = ((HttpsURLConnection) con).getResponseMessage();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//System.out.println("Response Message : " + responseMessage);
InputStream stream = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
System.out.println("hgfhfhfhgfgfghfgh");
BufferedReader br = new BufferedReader(isReader);
String result = "";
String line;
while ((line = br.readLine()) != null) {
result+= line;
}
System.out.println(result);
br.close();
con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
return subject;
}
I have calculated the signature correctly, because on hitting from postman client getting 200 response.
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
You missed a '/' before the question mark. It should be
URL url = new URL("https://email.us-east-1.amazonaws.com/?"+data);
I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?