I'm writting an Java application that do requests through REST API to Named Entity Recognition service (deeppavlov) running in a local network.
So I request data by following:
String text = "Welcome to Moscow, John";
List<String> textList = new ArrayList<String>();
textList.add(text);
JSONObject json = new JSONObject();
json.put("x", textList);
String URL = "http://localhost:5005/model";
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL))
.header("accept", "application/json")
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(json.toString()))
.build();
try {
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
System.out.println(response.body().getClass());
} catch (IOException | InterruptedException e) {
}
As result I get:
[[["Welcome","to","Moscow",",","John"],["O","O","B-GPE","O","B-PERSON"]]]
class java.lang.String
It is a string and I don't know how to convert it to object, array, map or list to iterate through. Please help.
It depends from the library that you are using to deserialize the string.
It seems that you are using org json code, so a possible solution uses a JSONTokener:
Parses a JSON (RFC 4627) encoded string into the corresponding object
and then use the method nextValue:
Returns the next value from the input. Can be a JSONObject, JSONArray, String, Boolean, Integer, Long, Double or JSONObject#NULL.
The code will be the following
Object jsonObject = new JSONTokener(jsonAsString).nextValue();
Related
I have a requirement to call a rest api put method which accepts one parameter Body(of type arrray[string]) which is to be passed to "BODY" not query parameter.
Below is the value that this parameter accepts:
[
"string"
]
These are the steps that I tried to make the call:
created an oauth consumer object that is used to sign the request and httpclient object to execute the request
consumer = new CommonsHttpOAuthConsumer("abc", "def");
requestConfig = RequestConfig.custom().setConnectTimeout(300 * 1000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
Creating the put request with json
URL url = new URL("http://www.example.com/resource");
String[] dfNames = {};
dfNames[0] = "test";
putreq = new HttpPut(url);
putreq.setHeader("Id","xyz");
StringEntity input = new StringEntity(dfNames); //Getting compilation error
input.setContentType("application/json");
putreq.setEntity(input);
Executing the request to get the response code
updateresponse = httpClient.execute(putreq);
int updatehttpResponseCode = updateresponse.getStatusLine().getStatusCode();
System.out.println("post Response Code :: " + updatehttpResponseCode);
if (updatehttpResponseCode == 200)
{
System.out.println("PuT request worked);
}
else
{
System.out.println("PuT request not worked");
}
OUTPUT:
I am getting a compilation error when running this since the string entity class cannot accept string array. Is there any other class which will accept the string[] array?
As discussed in the comments, the HTTP PUT body is just a string, so just convert the array to String (with Arrays.toString() or any other way) and use it.
I am doing some actions on a Response body after changing it to String:
Response myResponse = get(Some Endpoint);
String res = getIncidentResponse.getBody().asString();
//Some operations on the String
How to change back this "res" String to Response ?
Here is the conversion of String to Object.
ObjectMapper objm = new ObjectMapper();
Response response = objm.readValue(string, Response.class);
This should work!
I'm trying to send a POST request to a server, get the response, and parse it (it is a JSON file).
I am using Unirest for my POST request, simply as below:
HttpResponse<JsonNode> response = Unirest
.post("http://myserver.com/file")
.header("cache-control", "no-cache")
.header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
.header("Content-Type", "application/json")
.body("{some JSON body}")
.asJson();
// retrieve the parsed JSONObject from the response
JSONObject myObj = response.getBody().getObject();
// extract fields from the object
String msg = myObj.toString();
System.out.println(msg);
But I have problems getting the raw JSON text (I want to use JSONPath to parse the response).
How can I do that? All my attempts calling toString() methods failed so far.
The Unirest API supports this out of the box - Use asString() instead of asJson() to get the response as HttpResponse<String>.
HttpResponse<String> response = Unirest
.post("http://myserver.com/file")
.header("cache-control", "no-cache")
.header("Postman-Token", "02ec2fa1-afdf-4a2a-a535-353424d99400")
.header("Content-Type", "application/json")
.body("{some JSON body}")
.asString();
System.out.println(response.getBody());
You can do it like this:
InputStream inputStream = response.getRawBody();
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
String rawJson = buf.toString("UTF-8");
I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. I have also included every available scope from Spotify when I retrieve my access token. This is returning a response with an error message of:
{"error":{"message":"Error parsing JSON.","status":400}}
Here is what I have:
String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);
JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);
String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);
post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out
.println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);
client.close();
Please let me know if you have any insights into what is wrong.
I am assuming you are using the org.json library as well as Google's Gson library. Using both doesn't make sense in this context. You won't need
String dataStringify = GSON.toJson(entityObj);
as entity Object already is a JSON Object. entityObj.toString() should be enough.
The current JSON Data you are sending looks like this:
{
"data":
{
"name":"title",
"public":"false"
}
}
Spotify ask for an JSON Object like this:
{
"name": "New Playlist",
"public": false
}
You only have to send the Data Object dataObj.
I receive a post request from client. This request contains some json data which I want to part on the server side. I have created the server using httpcore. HttpRequestHandler is used for handling the request. Here is the code I thought would work
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
InputStream inputStream = entity.getContent();
String str = inputStream.toString();
System.out.println("Post contents: " + str);*/
But I cant seem to find a way to get the body of the request using the HttpRequest object. How can I extract the body from the request object ? Thanks
You should use EntityUtils and it's toString method:
String str = EntityUtils.toString(entity);
getContent returnes stream and you need to read all data from it manually using e.g. BufferedReader. But EntityUtils does it for you.
You can't use toString on stream, because it returns string representation of the object itself not it's data.
One more thing: AFAIK GET requests can't contain body so it seems you get POST request from client.
... and for MultipartEntity use this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
entity.writeTo(baos);
} catch (IOException e) {
e.printStackTrace();
}
String text = new String(baos.toByteArray());