I am using jersey client to post a file to a REST URI that returns the response as JSON.
My requirement is to read the response as (JSON) to a string.
Here is the piece of code that posts the data to the web service.
final ClientResponse clientResp = resource.type(
MediaType.MULTIPART_FORM_DATA_TYPE).
accept(MediaType.APPLICATION_JSON).
post(ClientResponse.class, inputData);
System.out.println("Response from news Rest Resource : " + clientResp.getEntity(String.class)); // This doesnt work.Displays nothing.
clientResp.getLength() has 281 bytes which is the size of the response, but clientResp.getEntity(String.class) returns nothing.
Any ideas what could be incorrect here?
I was able to find solution to the problem. Just had to call bufferEntity method before getEntity(String.class). This will return response as string.
clientResp.bufferEntity();
String x = clientResp.getEntity(String.class);
Although the above answer is correct, using Jersey API v2.7 it is slightly different with Response:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080");
Response response = target.path("api").path("server").path("ping").request(MediaType.TEXT_PLAIN_TYPE).get();
System.out.println("Response: " + response.getStatus() + " - " + response.readEntity(String.class));
If you still got problem with this, you may want to consider to use rest-assured
In my case I'm using Jersey 1.19 and Genson got in my classpath somehow? So the accepted answer throws com.owlike.genson.stream.JsonStreamException: Readen value can not be converted to String.
My solution was to read directly from the response stream:
private String responseString(com.sun.jersey.api.client.ClientResponse response) {
InputStream stream = response.getEntityInputStream();
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
return textBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
I am new to REST assured and API Automation, I have tried the following code using "GET" request:
public static void main(String args[]) throws IOException {
RestAssured.baseURI = "{Url}";
RequestSpecification httpRequest = RestAssured.given()
.contentType("x-www-form-urlencoded")
.formParam("grant_type", "")
.formParam("client_id", "")
.formParam("scope", "")
.formParam("client_secret","");
Response response = httpRequest.request(Method.GET);
JsonPath res = response.jsonPath();
//String BearerToken = response.getBody().asString();
System.out.println("The response is:" +res);
int code = response.getStatusCode();
System.out.println("The status code is" +code);
assertEquals(code, 200);
}
}
and I get the following output
io.restassured.path.json.JsonPath#12345xxx
This isn't right as I need to receive a proper JSON as a response.
Please Note: I have hidden some of the values pertaining to security risk.
Can someone please help me to resolve the same?
To print response from the Rest Assured you can use asString() method on Response object. You don't need to use JsonPath to print the results:
Response response = httpRequest.request(Method.GET);
System.out.println("The response is:" + response.asString());
OR you can use JsonPath's prettyPrint() method:
Response response = httpRequest.request(Method.GET);
JsonPath res = response.jsonPath();
res.prettyPrint(); //no need to call System.out.println
I'm updating groovy scripts from httpbuilder to httpbuilder-ng. These scripts interact with various webservices to get messages. I'm looking to parse the responses preferably using Jackson into objects. However, I can't seem to get the raw json response like I could in httpbuilder as httpbuilder-ng auto parses into a lazymap in all cases.
The old implementation using httpbuilder allowed you to use the body.text method to get the raw json string without it being parsed into a lazymap. This could then be used with ObjectMapper in Jackson to create my POJO's. However, httpbuilder-ng doesn't seem to support this.
I have already tried the method here for getting the raw json, but the body.text method does not seem to work in version 1.03 that I'm using http://coffeaelectronica.com/blog/2016/httpbuilder-ng-demo.html.
I have also tried to add my own custom encoders to override Groovy's default creation of JSON objects without any success. It is supposedly possible as detailed in the wiki https://http-builder-ng.github.io/http-builder-ng/asciidoc/html5/. If anyone has a code snippet of how to do this it would be appreciated!
Old httpbuilder code:
def http = new HTTPBuilder("http://${proxy}.domain.ie")
http.request(GET, TEXT) {
uri.path = "/blah/plugins/blah/queues"
headers.Accept = 'application/json'
headers.'Cookie' = "token=${token}"
response.success = { resp, json ->
assert resp.status < 300
LOGGER.info("GET queues request succeeded, HTTP " + resp.status)
ObjectMapper objectMapper = new ObjectMapper()
queues = objectMapper.readValue(json, Queue[].class)
}
response.failure = { resp ->
assert resp.status >= 300
LOGGER.info("GET queues request failed, HTTP " + resp.status)
return null
}
}
new http-builder-ng code:
def http = configure {
request.uri = "http://${proxy}.domain.ie"
request.headers["Accept"] = "application/json"
request.headers["Cookie"] = "token=${token}"
request.contentType = TEXT
}
return http.get {
request.uri.path = "/blah/plugins/blah/queues"
response.success { FromServer fs, Object body ->
return body.text // doesn't work
}
response.failure {
return null
}
}
Update
Found the solution. It was to add a custom parser and a closure using the FromServer.inputstream.text method.
def text = httpBuilder.get {
request.uri.path = '/blah/plugins/blah/queues'
response.parser('application/json') { ChainedHttpConfig cfg, FromServer fs ->
String text = fs.inputStream.text
}
}
I know we can send a json object via Postman as a POST request. However, I wish to send multiple such json Objects(hundreds) consecutively via. Postman.
Is there some way I can achieve that? I am stuck and will highly appreciate some solutions.
TIA:)
So I ended up sending the json data via. a java code through POST requests.
Since I needed this only for load testing, I didn't care much about the code efficiency here. Might be useful for someone
String line;
JSONParser jsonParser = new JSONParser();
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
while((line = br.readLine()) != null) {
JSONObject jsonObject = (JSONObject) jsonParser.parse(line);
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://url");
StringEntity params = new StringEntity(jsonObject.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);.
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
I am looking for some help with a datatable conversion into a JObject. I am using C# in visual studio along with the Newtonsoft JSON .net library. I have retrieved my datatable from my database.
From here I took the data table and processed it through this class:
public string DataTableToJSONString(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table,Formatting.Indented);
return JSONString;
}
Now that the object has been converted to a JSONString successfully (It throws no errors at this point) via the Newtonsoft JSON.net Library, I am unable to parse it into a JObject with this code:
Note: "json" is the string variable I placed the returned value from the DatatabletoDataTableToJSONString() method into..
JObject job = JObject.Parse(json);
I continuously get the following error...
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
The reason I need it in the form of a JObject it to pass it into the following post method for an API:
public static async Task<JObject> Post(string url, JObject data)
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = CreateBasicHeader(ClientContext.Username, ClientContext.Password);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send a request asynchronously and continue when complete
var requestbody = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, requestbody);
dynamic content = await response.Content.ReadAsAsync<JObject>();
// Check that response was successful or throw exception
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content[0].ToString(), ex);
}
// Read response asynchronously as a JObject
return content;
}
I would appreciate any help on this as I have been researching for 2 weeks with no luck. This one is really killing me. Thanks in advance to all who take the time to examine this.
UPDATE: I ended up adding in the following bit of code as I realized I was returning an array when I pulled the data table.
string jsonresult = JsonConvert.SerializeObject(dt);
JArray aray = JArray.Parse(jsonresult);
//I then have code for the API login credentials here....
foreach (JObject item in aray)
{
ApiClient.Post(Url, item).Wait();
}
This appears to pass in the JObjects just fine into the post method although I get the following error:"AggregateException was unhandled..." I set a break point and the flaw appears to happen at the:
try
{
response.EnsureSuccessStatusCode();
}
After attempting the response.ensuresuccessstatusCode(); The program of course jumps to the catch....
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content.message.ToString(), ex);
}
Again, any help would be appreciated. I am almost there with this. After it posts, I will be done.... Thanks again in advance to everyone. I apologize for being long winded.
Your problem is that JSON has two types of containers: arrays and objects:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
The corresponding LINQ to JSON class is JObject.
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
The corresponding LINQ to JSON class is JArray.
So, how does Json.NET serialize a data table? From the documentation Serialize a DataSet, we can see that each table is serialized as an array.
If you attempt to parse a JSON string whose root object is an array into a JObject, you will get this exception.
Instead, you must return a JArray, or better yet a JToken which is the root class for all JSON entities:
public static async Task<JToken> Post(string url, JObject data)
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = CreateBasicHeader(ClientContext.Username, ClientContext.Password);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send a request asynchronously and continue when complete
var requestbody = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, requestbody);
dynamic content = await response.Content.ReadAsAsync<JToken>();
// Check that response was successful or throw exception
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw new Exception("Status Code: " + response.StatusCode + "\r\nMessage: " + content[0].ToString(), ex);
}
// Read response asynchronously as a JToken
return content;
}
I am answering this thread and closing it as the original question has technically been answered. I simply converted the JArray into its respective JObjects with the following bit of code.
foreach (JObject item in aray)
{
ApiClient.Post(Url, item).Wait();
}
Although I am still working on debugging, I was technically able to pull the Object out of the array that I got from the data table.
Thanks all!!!!!
I am working on a web-service application using JSON.
In performing task I got success in directly fetching JSOn response by hitting the URL.
Now I have a task to request with a request parameter.
enter code here
private void callJSON_Webservice(String method,String paraLastModifiedDate) {
HttpConnection c=null;
InputStream is = null;
String feedURL = Constants.feedURL;
int rc;
try{
JSONObject postObject = new JSONObject();
postObject.put("CheckLatestDataDate",method);
postObject.put("LastModifiedDate", paraLastModifiedDate);
//c = new HttpConnectionFactory().getHttpConnection(feedURL);
c = (HttpConnection)Connector.open(feedURL + ConnectionManager.getConnectionString());
// Set the request method and headers
c.setRequestMethod(HttpConnection.GET);
c.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
c.setRequestProperty("Content-Length", "" + (postObject.toString().length() - 2));
//c.setRequestProperty("method", HttpConnection.GET);
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK){
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();
String json = StringUtils.convertStreamToString(is);
object = new JSONObject(json);
}catch (Exception e) {
System.out.println(e+"call webservice exception");
}
}
With this code I am getting EOF exception. I need to complete this small task as soon as possible. Please help me...!
Thanx in advance
Try replacing
is = c.openInputStream();
String json = StringUtils.convertStreamToString(is);
with following:
is = c.openInputStream();
StringBuffer buffer = new StringBuffer();
int ch = 0;
while (ch != -1) {
ch = is.read();
buffer.append((char) ch);
}
String json = buffer.toString();
Reference: convert StreamConnection to String