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();
Related
When I make the SOAP request from SOAP UI it returns normal answer, but when I try from Java code it returns not understandable characters. I tried to convert answer to UTF8 format, but it did not help. Please advise a solution, may be something wrong with my SOAP request. Example of response: OÄžLU, bu it must be OĞLU or MÄ°KAYIL instead of MİKAYIL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String userCredentials = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
con.setRequestProperty("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(myXML);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
System.out.println(responseStatus);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String xmlResponse = response.toString();
I tried:
ByteBuffer buffer = ByteBuffer.wrap(xmlResponse.getBytes("UTF-8"));
String converted = new String(buffer.array(), "UTF-8");
Try this:
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
The character encoding is set as part of the Content-Type header.
I believe you're accidentally mixing charsets, which is why it is not displaying properly.
Try adding the charset to Content-Type like so:
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
Would you try this?
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
String urly = "myurl";
URL url = new URL(myurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/xml");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(xml);
wr.flush();
i am not sure whether this sends the request using xml request structure which is stored in String "xml". I dont know any other way to send request using XML.
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(new InputStreamReader(con.getInputStream()));
String output;
StringBuffer res = new StringBuffer();
while ((output = iny.readLine()) != null) {
res.append(output);
}
iny.close();
wr.close();
//printing result from response
System.out.println(res.toString());
The response i am getting shows Invalid Request.
The generated XML was wrong, it needed to be checked.
I have a problem on HttpURLConnection in post method. Everything is working fine on get method however, when I try to use Post method. I'm getting this error message.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL
Here's my code snippet. I hope you could help me about this.
URL url = new URL(my url/userInfo);
String encoding = Base64.getEncoder().encodeToString(("username:password").getBytes("UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("x-csrf-token", "fetch");
String csrfToken = connection.getHeaderField("x-csrf-token");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String output = in.readLine();
in.close();
String content = data // expected data to retrieve
URL url2 = new URL(my URL);//another url to push the data retrieve
HttpURLConnection connection2 = (HttpsURLConnection) url2.openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
connection2.setRequestProperty("Authorization", "Basic " + encoding);
connection2.setRequestProperty("Accept", "application/json");
connection2.setRequestProperty("x-CSRFToken", csrfToken);
connection2.setRequestProperty("cache-control", "no-cache");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(data);//this is where the data will be pushed
osw.flush();
osw.close();
os.close();
the idea is, we need first to get the x-csrf-token and data from the first link, which is okay. After GET Method execution, the POST method will occur. unfortunately, the post method is not working. I'm getting the error message shown above. By the way, we tried to do a post method in POSTMAN and it' working fine.
Hoping you could help me about this.
I have returning response to client as
return Response.status(200).entity("Data was succesfully loaded into database").build();
I have to read this on client my client code
URL url=new URL(urlString);
// URLConnection connection=url.openConnection();
//connection.setDoOutput(true);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/json");
how to read these type of responses on client side
Once you have HttpURLConnection you can send data to the server (if this is needed, but looks like as it is, because you have POST request):
DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(yourData);
wr.flush();
wr.close();
Then you can check for response code (for e.g. if it is 200):
int responseCode = httpCon.getResponseCode();
And read data from response:
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
If you want to parse JSON you can use org.json or Gson.
I am new to facebook app development and i have been trying to post a simple message on the wall of the user.i have managed to get the access token .Here is the code for the POST request.I am using java servlets
String data = URLEncoder.encode("access_token", "UTF-8") + "=" + URLEncoder.encode(accessToken, "UTF-8");
data += "&" + URLEncoder.encode("message", "UTF-8") + "=" + URLEncoder.encode("finally", "UTF-8");
out.println("data is\n"+data);
// Send data
String u="https://graph.facebook.com/me/feed";
URL urls = new URL(u);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Well this code is not working and i can not post on the wall.Any suggestion as to where i might be wrong?
I'm pretty sure that it's because you don't specify the application/x-www-form-urlencoded content type, try this:
URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(data);
out.flush();
out.close()
Edit
Ok, so there are two more things that might cause this problem:
You also need to specify the content length.
You might need to read the response to make it count..
This code was tested and it works:
StringBuffer buffer = new StringBuffer();
buffer.append("access_token").append('=').append(ACCESS_TOKEN);
buffer.append('&').append("message=").append('=').append("YO!");
String content = buffer.toString();
URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(content.length()));
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();