json parsing in blackberry? - json

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

Related

API Automation: Receiving Output like "`io.restassured.path.json.JsonPath#12345xxx " on "GET" request

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

How to send multiple requests via Postman

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();
}
}

How to POST Json data without jquery from an action method and read the response

Clarification: POST requests are between different websites or different controller in the same project.
I want to POST Json data to another action method. I am using Newtonsoft for json serialization, the thing is that in JsonMethod, the field Name comes with null. Am I missing something?
My model:
class Person
{
[JsonProperty("name")]
public string Name{get;set;}
}
The action method that post the json:
public ActionResult Method1()
{
Person p = new Person(){Name = "Test"}
string urlToRedirect = "..urlRoute../JsonMethod";
var res = SendRequest(urlToRedirect, p);
//...do anything with res
}
The method that receive the Model
[HttpPost]
public ActionResult JsonMethod(Person p)
{
if(p.Name == "Test")
return Json("ok");
else return Json("bad");
}
The method that send the request
public async bool SendRequestAsync(string requestUrl, object data)
{
string json = JsonConvert.SerializeObject(obj, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
if (request != null)
{
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
using (var stream = new StreamWriter(await request.GetRequestStreamAsync()))
{
stream.Write(json);
}
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response != null && response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
if (response != null)
{
Stream responseStream = response.GetResponseStream();
//return true or false depending on the ok
return GetResponseModel(responseStream);
}
}
}
}
catch (WebException ex)
{
var response = ex.Response;
Stream respStream = response.GetResponseStream();
//return true or false depending on the ok
return GetResponseModel(respStream);
}
catch (Exception e)
{
return false;
}
return false;
}
My mistake was the "name" attribute property on person, it must be with capital Letter "Name". Thats why it was coming with null.
[JsonProperty("Name")]

The remote server returned an error (401) unauthorized when i try to save my json data

i want to post the json data to a webservice.
Here is the method:
public static Int32 SaveCashSale(string username, string key, CashSale cashSale)
{
try
{
// Customize URL according to geo location parameters
var url = string.Format(cashSaleUrl, username, key);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string jsonData = new JavaScriptSerializer().Serialize(new
{
activity_date = cashSale.activity_date = DateTime.Now.ToString(),
added_by = cashSale.added_by,
amount_paid = cashSale.amount_paid,
balance = cashSale.balance,
currency = cashSale.currency,
customer = cashSale.customer,
grand_total = cashSale.grand_total,
modified_by = cashSale.modified_by,
price_type = cashSale.price_type,
sub_total = cashSale.sub_total,
total_quantity = cashSale.total_quantity,
workspace = cashSale.workspace,
});
streamWriter.Write(jsonData);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}
catch (Exception)
{
throw;
}
}
The system the following error message:
the remote server returned an error (401) unauthorized. at this line of the code:
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The url format is:
private const string ashSaleItemUrl = "http://avaris.kwekud.com/api/v1/sales/cashsale/?username={0}&api_key={1}";
What is wrong with my code and how can i solve it ?

reading JSON response as string using jersey client

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;
}
}