Print Wit.ai response in console [java] - java

hi all I'm trying to send a request to Wit to a simple wit application that i've created and I'm doing this in java. I'm trying to print the wit response into the console but the only thing that prints is the following line:
class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
The code that I am using to send the request is a code that I have found on this forum, I repost it for be more specific:
public static String getCommand(String command) throws Exception {
String url = "https://api.wit.ai/message";
String key = "MY_SERVER_KEY";
String param1 = "my_param";
String param2 = command;
String charset = "UTF-8";
String query = String.format("v=%s&q=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty ("Authorization", "Bearer " + key);
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
return response.toString();
}
how can i return the wit response?
EDIT:
I'm trying with apache as you suggested to me, but it keeps to send me error 400.
Here the code:
public static void getCommand2(String command) throws Exception {
String query = URLEncoder.encode(command, "UTF-8");
String key = "my_key";
String url = "https://api.wit.ai/message?v="+my_code+"q"+query;
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("Authorization: Bearer", key);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}

You don't have to use Apache
Taken from the Wit.ai android-sdk.
public static String convertStreamToString(InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
is.close();
return sb.toString();
}
The problem you were having is that the InputStream's toString method is only returning it's class name. Another thing you can try is using HTTPURLConnection rather than just the simple URLConnection, since you know it will be an HTTP request as opposed to another protocol.

Related

Posting JSON to REST API from Java Servlet

I'm having issues trying to send over a JSON string to a REST API. Long story short, I'm taking user input in a form, sending it over to a java servlet to validate and work with it a bit, and then trying to send it to an endpoint.
I have the following method being called on in my doPost method in my servlet, I am using printwriter pw to be able to read back data being returned in my response in the browser console at this point.
String jsonData = //JSON STRING HERE\\
String username = //USERNAME\\
String password = //PASSWORD\\
String endpointURL = //ENDPOINT URL HERE\\
pw.println(sendJson(jsonData, username, password));
private String sendJSON(String jsonData, String usrname, String usrpass) {
try {
String auth = usrname + ":" + usrpass;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
URL url = new URL(endpointURL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(5000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json; utf-8");
http.setRequestProperty("Authorization", authHeaderValue);
http.setDoOutput(true);
//POST Json to URL using HttpURLConnection
//try(OutputStream os = http.getOutputStream()) {
OutputStream os = http.getOutputStream();
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
//}
/*String responseBody;
try(BufferedReader br = new BufferedReader(
new InputStreamReader(http.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//System.out.println(response.toString());
responseBody = response.toString();
return responseBody;
}
return responseBody;*/
BufferedReader in = new BufferedReader(
new InputStreamReader(http.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
return e.toString();
}
}
}
I was having issues with the try's so I rewrote it to try and just get functionality right away first. Right now I'm receiving "java.io.IOException: Server Returned HTTP response code: 500 for URL: //URL HERE\"
Would anybody have any tips to point me in the right direction? I feel like I'm just missing like a small piece of the puzzle at this point, and I'm having a hard time finding any tutorials showing what it is that I'm trying to do. Thank you so much to anyone for any tips/pointers!
Made sure I was able to authenticate and that wasn't the issue by just connecting and returning:
int statusCode = http.getResponseCode();
String statusCodeString = Integer.toString(statusCode);
return statusCodeString;
This worked fine, received 403 response when setting wrong password/username and 400 response when I change to correct.
I attempted using HttpClient as well instead, but was having issues trying to get that to work at all. I also had an error earlier with week trying to do this with a certificate error, but after reimporting the cert to my cacerts file this was resolved (unrelated to this issue I believe).

How send GET request with value of parameter containing a space?

I'm testing this code below to send GET request with parameters and this code fails when the value of parameter is a string containing a space, Ex: http://company.com/example.php?value=Jhon 123. Already if i send Jhon123 (withou any space) works fine.
Why this happens?
private static void sendGet(String site, String params) throws Exception {
site += params;
URL obj = new URL(site);
try {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + site);
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());
} catch (Exception ex) {
}
}
You should URL Encode your request.
You can use URLEncoder to encode your parameter:
String url = "http://company.com/example.php?value=" + URLEncoder.encode("Jhon 123", "utf-8");

Reading rest service of content type application/vnd.oracle.adf.resourceitem+json

I have a webservice whose content type is application/vnd.oracle.adf.resourceitem+json.
The HttpEntity of the reponse obtained by hitting this service is looks like this
ResponseEntityProxy{[Content-Type: application/vnd.oracle.adf.resourceitem+json,Content-Length: 3,Chunked: false]}
When I try to convert this HttpEntity into String it gives me a blank String {}.
Below are the ways I tried to convert the HttpEntity to String
1.
String strResponse = EntityUtils.toString(response.getEntity());
2.
String strResponse = "";
String inputLine;
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
try {
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
strResponse += inputLine;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
3.
response.getEntity().writeTo(new FileOutputStream(new File("C:\\Users\\harshita.sethi\\Documents\\Chabot\\post.txt")));
All returns String -> {}.
Can anyone tell me what am I doing wrong?
Is this because of the content type?
The above code is still giving the same response with empty JSON object. So I modified and wrote the below code. This one seems to run perfectly fine.
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization", getAuthToken());
con.addRequestProperty("Content-Type", "application/vnd.oracle.adf.resourceitem+json;charset=utf-8");
String input = String.format("{\"%s\":\"%s\",\"%s\":\"%s\"}", field, value, field2, value2);
System.out.println(input);
OutputStream outputStream = con.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
con.connect();
System.out.println(con.getResponseCode());
// Uncompressing gzip content encoding
GZIPInputStream gzip = new GZIPInputStream(con.getInputStream());
StringBuffer szBuffer = new StringBuffer();
byte tByte[] = new byte[1024];
while (true) {
int iLength = gzip.read(tByte, 0, 1024);
if (iLength < 0) {
break;
}
szBuffer.append(new String(tByte, 0, iLength));
}
con.disconnect();
returnString = szBuffer.toString();
Authentication method
private String getAuthToken() {
String name = user;
String pwd = this.password;
String authString = name + ":" + pwd;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
System.out.println(new String(authEncBytes));
return "Basic " + new String(authEncBytes);
}
In case anybody faces the same issue. Let me share the challenged I faced and how I rectified those.
The above code works for all content-types/methods. Can be used for any type (GET, POST, PUT,DELETE).
For my requirement I had a POST webservice with
Content-Encoding →gzip
Content-Type →application/vnd.oracle.adf.resourceitem+json
Challenges : I was able to get the correct response code but I was getting junk characters as my response string.
Solution : This was because the output was compressed in gzip format which needed to be uncompressed.
The code of uncompressing the gzip content encoding is also mentioned above.
Hope it helps future users.

URLConnection with basic authorization

Im trying to get all the xml data from a myanimelist request.
I've ried this code (see code below) on an other url and this worked.
Now, for myanimelist you need an account to request queries. I have tried different things like changing the location of uc.setRequestProperty ("Authorization", getBasicAuthenticationEncoding()); before and after the openConnection(); But nothing seems to work. The code below gives me this error: server returned HTTP response code: 401 for URL: http.
Can someone help me with this?
Code: (i used fake pwds for the example)
System.out.println(getXMLFromUrl("https://myanimelist.net/api/anime/search.xml?q=" + "2017"));
private String getBasicAuthenticationEncoding() {
String username= "username";
String password = "mypwd";
String userPassword = username + ":" + password;
#SuppressWarnings("static-access")
String basicAuth = "Basic " + new String(new Base64().encode(userPassword.getBytes()));
return basicAuth;
}
public String getXMLFromUrl(String url) throws IOException {
URL u = new URL(url);
URLConnection uc = u.openConnection();
uc.setRequestProperty ("Authorization", getBasicAuthenticationEncoding());
InputStream in = uc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
sb.append(line + "\n");
}
br.close();
return sb.toString();
}

Place detail request failing - reference too long

I have a small java app that, given a list of references for google places, must get back the Id's for each of said google places (long story short, we were storing references for places instead of their Id's, and only now realized that references are not unique per place).
My app works perfectly for about 95% of the places in the list, but fails with a "NOT_FOUND" status code for some records. Some investigation reveals that the place reference for these particular places is (when combined with the https://maps.googleapis.com/maps/api/place/details/json?sensor=false&key=myApiKey prefix) about 2 characters too long for a URL. The last couple of characters are getting truncated.
My initial thought was that I would just make a POST request to the google places API, but I'm getting back "REQUEST_DENIED" status code from the google servers when sending the same into as a POST request.
Is there anyway around this, or is this just an emergent bug with the google places API (now that the number of places has pushed the reference too long?).
I should also note that the places that fail are all recently added by our application.
This is what my current (working for 95%) code looks like:
public static JSONObject getPlaceInfo(String reference) throws Exception
{
URL places = new URL("https://maps.googleapis.com/maps/api/place/details/json?sensor=false&key="+apiKey+"&reference="+reference);
URLConnection con = places.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer input = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
input.append(inputLine);
in.close();
JSONObject response = (JSONObject) JSONSerializer.toJSON(input.toString());
return response;
}
and this is what my "ACCESS_DENIED" post code looks like:
public static JSONObject getPlaceInfo(String reference) throws Exception
{
String data = URLEncoder.encode("sensor", "UTF-8") + "=" + URLEncoder.encode("true", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(apiKey, "UTF-8");
data += "&" + URLEncoder.encode("reference", "UTF-8") + "=" + URLEncoder.encode(reference, "UTF-8");
URL places = new URL("https://maps.googleapis.com/maps/api/place/details/json");
URLConnection con = places.openConnection();
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer input = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
input.append(inputLine);
in.close();
JSONObject response = (JSONObject) JSONSerializer.toJSON(input.toString());
return response;
}
An example of the reference that fails is:
CnRtAAAAxm0DftH1c5c6-krpWWZTT51uf0rDqCK4jikWV6eGfXlmKxrlsdrhFBOCgWOqChc1Au37inhf8HzjEbRdpMGghYy3dxGt17FEb8ys2CZCLHyC--7Vf1jn-Yn1kfZfzxznTJAbIEg6422q1kRbh0nl1hIQ71tmdOVvhdTfY_LOdbEoahoUnP0SAoOFNkk_KBIvTW30btEwkZs
Thanks in advance!
You're sending your request parameters in the body, which isn't supported by the API. There's a good answer about GET and request params at:
HTTP GET with request body
The following code should work for Place detail requests:
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_DETAILS = "/details";
private static final String OUT_JSON = "/json";
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_DETAILS);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&reference=" + URLEncoder.encode(reference, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString()).getJSONObject("result");
jsonObj.getString("name");
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}

Categories

Resources