get stale body on OkHttp 2.0 - java

My webservice sends these headers:
Cache-Control: public, max-age=60, max-stale=86400
Now on my first call, this is the response:
code = 200
cacheResponse = null
networkResponse = Response{code=200, ...}
body = correctdata
The second call within a minute is:
code = 200
cacheResponse = Response{code=200, ...}
networkResponse = null
body = correctdata
Now, after a minute, I delete my webservice, and do another call. Now because of the max-stale header, I expect to be able to retrieve the cacheResponse, to show the old data.
The response is this:
code = 404
cacheResponse = Response{code=200, ...}
networkResponse = Response{code=404, ...}
body = pagenotfounditem
Now the cacheResponse.body() returns null, so I can't use the old data, so crashes on String cb = cacheBody.string();. A code sample is shown below:
if(response.networkResponse() != null) {
System.out.println("There is no cache, or cache is invalidated.");
if(!response.isSuccessful()) {
System.out.println("Call is not successful");
if(response.cacheResponse() != null) {
System.out.println("There is a cache");
ResponseBody cacheBody = response.cacheResponse().body();
String cb = cacheBody.string();
System.out.println("cacheBody: " + cb);
return cb;
}
}
}
ResponseBody body = response.body();
if(body != null) {
String b = body.string();
System.out.println("body: " + b);
return b;
}
Is this behaviour intended, and if so, how can I get the cached response data?

Add this request header:
Cache-Control: max-stale=86400
That'll cause OkHttp to use the cache only.

Related

How to know AccountTeam in salesforce is enabled or disabled through any API with core java code?

JAVA Code- I have coded the following code using rest API to connect with salesforce, following code is from the URL to get Schema or fields of AccountTeamMember(a standard object) object which after establishing connection with salesforce org through RESTAPI
String schemaUrl = instanceurl + "/services/data/v54.0/sobjects/AccountTeamMember/describe";
log.info("schemeaUrl " + schemaUrl);
String responseString = "emptyschema";
Header printHeader = new BasicHeader("X-PrettyPrint", "1");
Header oAuthHeader = new BasicHeader("Authorization", "OAuth " + accesstoken);
HttpGet schemaHttpGet = new HttpGet(schemaUrl);
schemaHttpGet.addHeader(oAuthHeader);
schemaHttpGet.addHeader(printHeader);
int count = 0;
response = httpClient.execute(schemaHttpGet);
log.info("after executing HTTPGet : " + response);
int iStatusCode = response.getStatusLine().getStatusCode();
log.info("iStatusCode : " + iStatusCode);
if (iStatusCode == 200) {
HttpEntity httpEntity = response.getEntity();
log.warn("httpEntity : " + httpEntity);
if (httpEntity != null) {
log.info("before responseString " + responseString);
responseString = EntityUtils.toString(httpEntity);
log.info("after responseString " + responseString);
**** here after running this code i got all fields of AccountTeamMember(a standard object associated with account object) in Json format if I keep AccountTeams enable, through RestAPI I am able to get all fields as json object and if disable then 404 satus code
so here is My question Is there any other way to know AccountTeams is enabled for Account object other than this 404 status code and manually login to salesforce org? ****

how to insert an array to JSONArray with rest assured

I want to insert the array with Rest Assured.
tokenUUIDs - is an array ( A variable that I defined in a previous step).
When I run the code - tokenUUIDs received a correct value But ArraytokenUUIDs have not received something good. He received : [[Ljava.lang.String;#6fc0bbc6]
This is my Method:
public static void releaseTokens(String[] tokenUUIDs )
{
try{
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject releaseTokens = new JSONObject();
releaseTokens.put("partnerCode", commonOps.partnerCode);
releaseTokens.put("apiAccessToken",commonOps.openAccessToken);
releaseTokens.put("sessionUUID",SessionUUID);
releaseTokens.put("taskUUID","TaskUUID");
JSONArray ArraytokenUUIDs = new JSONArray();
ArraytokenUUIDs.add(tokenUUIDs);
releaseTokens.put("tokenUUIDs", ArraytokenUUIDs);
request.body(releaseTokens.toJSONString());
Response response = request.post((getData("APIenv") + "/api/sessions/releaseTokens.php"));
int code = response.getStatusCode();
Assert.assertEquals(code, 200);
System.out.println("Status code for releaseTokens.php is" +code );
ResponseBody bodyreleaseTokens = response.getBody();
System.out.println("Body bodyreleaseTokens.php " + bodyreleaseTokens.asString() );
String statusbodyreleaseTokens = bodyreleaseTokens.asString();
String status = response.getBody().jsonPath().getString("status");
Assert.assertEquals(status, "OK");
test.log(LogStatus.PASS, "bodyreleaseTokens is done" );
}
catch (Exception e)
{
test.log(LogStatus.FAIL, "bodyreleaseTokens is not done");
test.log(LogStatus.FAIL, e.getMessage());
fail ("bodyreleaseTokens is not done");
}
Try to add every token individually
for (String s : tokenUUIDs){
ArraytokenUUIDs.add(s);
}
Change
ArraytokenUUIDs.add(tokenUUIDs);
to
for (String tokenUUID : tokenUUIDs) {
ArraytokenUUIDs.add(tokenUUID);
}
Also consider that variables in java are named with lowercase first letter as a standard to avoid confusion with classes.

How can I get specific object from methods response JSON

I want to call another method if the condition is satisfied with the response of first method. But the response is in JSON and has many objects. I want to check if "RESPCODE" is "01" and if it is call a method.
Method:
#Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction is successful " + inResponse);
if(inResponse.toString().equals("01")) {
CheckoutProcess();
} else {
Toast.makeText(getApplicationContext(), "Transaction Failed ", Toast.LENGTH_LONG).show();
Log.d("LOG", "Payment Transaction : " + inResponse);
}
}
Response:
TXNAMOUNT = 1000.00
PAYMENTMODE = PPI
CURRENCY = INR
TXNDATE = 2018-04-17 18:56:08.0
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Success
GATEWAYNAME = WALLET
BANKTXNID =
BANKNAME = WALLET
org.json library should be enough if it is only one or two properties you are interested in.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
int respcode = jsonObj.getInt("RESPCODE");
You can see a complete example here:
How to parse JSON in Java

C# trying to "get" from server

So I have a tomcat server that I can successfully send a query such as... localhost:8080/AnarchyChatServer/AnarchyChatServlet?message=asdf&sendto=x&sendfrom=y
This will run the doGet() in my tomcat server, I have nothing in doPost()
Which will simply return asdf x y in the response BODY as HTML. Now in my C# I am trying to build the query string and send the message as such...
public string sendMessage(string message)
{
string url = "";
string response = "No server response.";
using (var wb = new WebClient())
{
UriBuilder baseUri = new UriBuilder("localhost:8080/AnarchyChatServer/AnarchyChatServlet");
message = message.Replace("&", "(AMPERSAND)");
message = message.Replace("?", "(QUESTIONMARK)");
string queryToAppend = "message=" + message;
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
queryToAppend = "sendto=" + sending;
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
queryToAppend = "sentfrom=" + account[0];
if (baseUri.Query != null && baseUri.Query.Length > 1)
baseUri.Query = baseUri.Query.Substring(1) + "&" + queryToAppend;
else
baseUri.Query = queryToAppend;
url = baseUri.Uri.ToString();
try
{
response = wb.DownloadString(baseUri.Uri);
}
catch (System.Net.WebException)
{
}
}
return response;
}
Ignore the hideous code reuse and whatnot. Basically the query building seems to work correct as if I output "url" it will return the proper url with the query string, but the issue is is that when I print out response after the call has been made to the server it just says "No server response" as it was initialized at the top of the C# code. Basically I'm wondering how I can query the server. Any insight would be helpful.
Your first problem is the lack of protocol in the Uri. Try this:
UriBuilder baseUri = new UriBuilder("http://localhost:8080/AnarchyChatServer/AnarchyChatServlet");
By the way... To debug these issues in the future, use:
catch (Exception ex)
{ <- breakpoint here
}
And examine ex. Or turn on breaking on thrown CLR exceptions in Visual Studio and debug the code (or just don't swallow the exception). Then you would see this:
Ignoring exceptions when debugging code is not a good idea in general...

Jax-RS and Xmlhttp Communication

I have a REST Server in Java JAX-RS and an HTML page.
I want to send a JSON array, a username, and an accountID from the HTML page through an xmlhttp POST request by making all of them a single big String so I can use the xmthttp.send() method.
The HTML sending code is:
function sendData() {
var req = createRequest();
var postUrl = "rest/hello/treeData";
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
var accID = "onthespot";
var username = "alex";
req.open("post", postUrl, true);
req.setRequestHeader("Content-type","text/plain");
req.send("data=" + JSON.stringify(dsdata) + "&username=" + username + "&accID=" + accID);
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
And the Server JAX-RS code is:
#Path("/treeData")
#POST
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String storeTreeData(
#QueryParam("data") String data,
#QueryParam("username") String username,
#QueryParam("accID") String accID) {
System.out.println("Data= " + data + "\nAccID= " + accID + "\nUsername= " + username);
return "Done";
}
The problem is that all the variables are printed as null..
the storeTreeData function should find the data , username , accID variables through #QueryParam and store them isn't that right?
Anyone know what's the problem here?
PS:The xmlhttp request is initiallized correctly and the connection is made but the parameters are not passed on the server.
What you try to do:
#QueryParam is used to get parameters from the query of the request:
http://example.com/some/path?id=foo&name=bar
In this example id and name can be accessed as #QueryParam.
But you are sending the parameters in the body of your request.
What you should do:
To get the parameters from the body, you should use #FormParam together with application/x-www-form-urlencoded:
#Path("/treeData")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public Response storeTreeData(
#FormParam("data") String data,
#FormParam("username") String username,
#FormParam("accID") String accID) {
// Build a text/plain response from the #FormParams.
StringBuilder sb = new StringBuilder();
sb.append("data=").append(data)
.append("; username=").append(username)
.append("; accId=").append(accID);
// Return 200 OK with text/plain response body.
return Response.ok(sb.toString()).build();
}
Edit:
You should also use
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in your JavaScript code.

Categories