OpenWeather api returing null values - android-studio

I am trying to fetch data from openweather api using retrofit2 and Gson but it always return the null value error.
I tried to debug and the response returned is fine yet it returns null.
Here is my code..
POJO CLASSES was taken from here.
http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22
How I am trying to fetch.
API interface
public interface Api {
String api_key = "b6907d289e10d714a6e88b30761fae22";
String BASE_URL= "http://api.openweathermap.org/data/2.5/";
#GET("weather")
Call<Weather> getWeather(#Query("lat") String latitude, #Query("lon") String longitude, #Query("appid") String api_key);
}
LoadWeather()
public void LoadWeather()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<Weather> weatherCall = api.getWeather("12.9716", "77.5946", api_key);
weatherCall.enqueue(new Callback<Weather>() {
#Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
Weather weather = response.body();
String temp = weather.getList().get(0).getMain().getTemp().toString();
Log.d(TAG,"onReponse :"+weather);
}
#Override
public void onFailure(Call<Weather> call, Throwable t) {
}
});
}

You are using the App Key 'b6907d289e10d714a6e88b30761fae22' which is used for
the examples (samples.openweathermap.org).
You have to subscribe to get your own API key.

Is it possible you forgot to include which API you want to use in the URL?
Maybe you need:
String BASE_URL= "http://api.openweathermap.org/data/2.5/weather?";

Related

How to return error message in Rest API when return value is a Byte array? [duplicate]

I have an Azure Function 2.x that reside on a static class that looks like this
[FunctionName("Register")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req, ILogger log)
{
MyTypeClass defReturn = new MyTypeClass();
HttpStatusCode defCode = HttpStatusCode.BadRequest;
/*
* Logics that might or might not changes
* defReturn and defCode value
*/
return StatusCode((int) defCode, JsonConvert.SerializeObject(defReturn))
}
How can i achieve the return StatusCode((int) defCode, JsonConvert.SerializeObject(defReturn)) part ? is there any such method or equivalent in Azure Functions 2.x ?
in Azure Functions 1.x i can do the equivalent with req.CreateResponse(defCode, defReturn) where req is HttpRequestMessage , but i'm trying to stick with 2.x template/standard
Additional explanation : The said Code should return HTTP 400 Bad Request with the defReturn as it's response body to the client. But when i change the defCode to HttpStatusCode.Accepted, it should return HTTP 202 Accepted with the same response body. How can i achieve this ?
Additional explanation#2 : (If i remember correctly) in ASP.NET Core 1.x i can exactly do like that, returning IActionResult by calling a static method StatusCode not StatusCodes (which is a static class that contains HTTP codes constants
Thank you
Quite late reply, but I was stumbling into the same problem today, so maybe this is helpful for other searchers
Option 1: Default Codes
This is stated in detail on the blog Here
Some codes like 200 and 400 are predefined and can be used by
return new OkObjectResult("Your message"); // 200
return new BadRequestObjectResult("Your error message"); // 400
These functions are not available for every known Status Codes but some of the most frequent.
Option 2: Manual setting Code
If you need specific codes, that are not provided by default, you can use the base classes and create them yourself.
To achieve the Teapot Response for example, you can just use
using Microsoft.AspNetCore.Http;
var result = new ObjectResult("Your message");
result.StatusCode = StatusCodes.Status418ImATeapot;
return result;
In this example, the Statuscode is used from the StatusCodes class, but you can use enter other codes as well (usually, just stick to these codes)
Also, the ObjectResult class offers additional formatting options, if needed.
You can create a model class in which you can define two properties, i.e. one form your status code and one for you Json object and later on you can return the complete model. Code sample would be like below:
public static class QueueTriggerTableOutput
{
[FunctionName("QueueTriggerTableOutput")]
[return: Table("outTable", Connection = "MY_TABLE_STORAGE_ACCT_APP_SETTING")]
public static Person Run(
[QueueTrigger("myqueue-items", Connection = "MY_STORAGE_ACCT_APP_SETTING")]JObject order,
ILogger log)
{
return new Person() {
PartitionKey = "Orders",
RowKey = Guid.NewGuid().ToString(),
Name = order["Name"].ToString(),
MobileNumber = order["MobileNumber"].ToString() };
}
}
public class Person
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Name { get; set; }
public string MobileNumber { get; set; }
}
on the receiving front, you can catch both the property.
P.S.- you have to change the return type of your function.
Hope it helps.

How to mock two APIs with MockWebServer Android test cases

I am performing instrumentation testing, in that I am invoking one of the activities which call 2 APIs when activity is created.
Now I want to write instrumentation test cases for this activity, where I have to mock the API response with mockWebServer of mockito. My mocking code works fine when I call one single API, but it fails when two APIs are getting called simultaneously.
Even there is another scenario let's say, we have API to fetch recent message data, but before that, we always authenticate the user by sending refresh token.
In such cases, we need to call API which authenticates the user and then another API to fetch message data. Hence we need to call 2 APIs one after another, let's say in a single method. How will I mock authentication API response and messages API response while writing test cases of that single method?
How should I deal with this issue? Is there any other approach to deal with such a situation where we need to call more than one API at the same time?
Also, I have used SystemClock.sleep(4000); as my callbacks were getting performed asynchronously.
Below is my code to mock API:
public class MyAPIActivityTest {
#Rule
public InstantTaskExecutorRule mInstantTaskExecutorRule = new InstantTaskExecutorRule();
#Rule
public ActivityTestRule<MyAPIActivity> myAPIActivityTestRule = new ActivityTestRule<>(MyAPIActivity.class, true, false);
MockWebServer mockWebServer;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void checkVisibilityOfTaskListMockedValidData() throws Exception {
myAPIActivityTestRule.launchActivity(null);
String fileName = "json_files/valid_api_response.json";
mockWebServer = new MockWebServer();
int PORT_NUMBER = 50205;
mockWebServer.start(PORT_NUMBER);
ApiUrls.BASE_QUERY_URL = mockWebServer.url("/").toString();
mockWebServer.enqueue(new MockResponse()
.setBody(getStringFromFile(getContext(), fileName)));
SystemClock.sleep(4000);
Assert.assertEquals(View.VISIBLE, myAPIActivityTestRule.IvDataIsPresent.getVisibility());
Assert.assertEquals(View.GONE, myAPIActivityTestRule.IvDataNotPresent.getVisibility());
}
#After
public void tearDown() throws Exception {
mockWebServer.shutdown();
}
public static String convertStreamToString(InputStream inputStream) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append(StringCharacters.NEW_LINE);
}
reader.close();
return stringBuilder.toString();
}
public static String getStringFromFile(Context context, String filePath) throws Exception {
final InputStream stream = context.getResources().getAssets().open(filePath);
String text = convertStreamToString(stream);
stream.close();
return text;
}
}
Any help is appreciated. Thanks in advance.

Unable to get from ServiceStack API using JsonServiceClient

I am trying to get all equipment types from my API using the following code.
client = new JsonServiceClient(environment.apiEndpoint);
var equipmentTypes = new GetEquipmentTypes();
var response = this.client.get(equipmentTypes);
I can see that it is in the network tab. The data is being transferred.
public class GetEquipmentTypeResponse
{
public IEnumerable<EquipmentType> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
Is the return DTO from the API.
[Route("/api/EquipmentTypes", "GET")]
public class GetEquipmentTypes : IReturn<GetEquipmentTypeResponse>
{
}
Is the ServiceInterface used.
IEnumerable<EquipmentType> response = db.Select<EquipmentType>(x=>x.Name == request.Name);
return new GetEquipmentTypeResponse { Results = response,
ResponseStatus = new ResponseStatus { }};
Is what the API returns.
The API is written in asp.net. The client side is angular 6 (typescript).
I have attached two images, which is the request and the response given.
This is the request which is sent to the API.
This is what the API responds.
This is what I get from var response. (console.log(response))
The screenshot shows that the response is being returned fine, the Promise result is just not being awaited, try:
var response = await this.client.get(equipmentTypes);

How to validate a REST Assured request across multiple java methods?

I am writing REST Assured tests using Cucumber.
Here is my feature file:
Given I want to GET a client
When I request a client
Then the status code is "theStatusCode"
And the id returned is "expectedClientId"
The below method is called within the Step Definition of the "And" in my feature file
public void validateResponseBody(String expectedClientId){
RestAssured.given()
.when()
.get(completeURL)
.then()
.statusCode(Integer.parseInt(theStatusCode))
.and()
.body("Client.Id", equalTo(expectedClientId));
}
This method currently works, but how do I split the validation?
I.e. how can I break this up to validate the Status Code in one method, & validate the Client Id in another method without having to send the request twice?
Save response to variable:
public void validate() {
ValidatableResponse response = RestAssured.given()
.when()
.get(completeURL)
.then();
validateStatusCode(response, statusCode);
validateResponseBody(response, expectedClientId);
}
public void validateStatusCode(ValidatableResponse response, String statusCode) {
response
.statusCode(Integer.parseInt(theStatusCode));
}
public void validateResponseBody(ValidatableResponse response, String expectedClientId) {
response
.body("Client.Id", equalTo(expectedClientId));
}
I suggest to make changes in Feature File.
New File should be given below. You don't need a when statement here.
Scenario: I want to GET a client
Given I request a client
Then the status code is "theStatusCode"
And the id returned is "expectedClientId"
#Given("I request a client$")
public void validate()
{
ValidatableResponse validatableResponse = RestAssured.given()
.when()
.get(completeURL)
.then();
}
#Then("the status code is \"([^\"]*)\"$")
public void validateStatusCode(String statusCode)
{
validatableResponse.assertThat().statusCode(Integer.parseInt(theStatusCode));
}
#And("the id returned is \"([^\"]*)\"$")
public void validateClientId(String expectedClientId)
{
validatableResponse.assertThat().body("Client.Id", equalTo(expectedClientId));
}

Render an MVC3 action to a string from a WCF REST service method

I have a WCF REST service that takes some parameters and sends an email. The template for the email is an MVC3 action. Essentially I want to render that action to a string.
If it were an ASP.NET WebForm, I could simply use Server.Execute(path, stringWriter, false). However when I plug in the path to my action, I get Error executing child request.
I have full access to HttpContext from my service (AspNetCompatibilityRequirementsMode.Allowed).
I know there are other answers out there for rendering actions to strings from within the context of a controller. How do I do this when I'm outside that world, but still on the same server (and, for that matter, in the same app)?
I cobbled together an answer based on several different google searches. It works, but I'm not 100% sure it's as lean as it could be. I'll paste the code for others to try.
string GetEmailText(TemplateParameters parameters) {
// Get the HttpContext
HttpContextBase httpContextBase =
new HttpContextWrapper(HttpContext.Current);
// Build the route data
var routeData = new RouteData();
routeData.Values.Add("controller", "EmailTemplate");
routeData.Values.Add("action", "Create");
// Create the controller context
var controllerContext = new ControllerContext(
new RequestContext(httpContextBase, routeData),
new EmailTemplateController());
var body = ((EmailTemplateController)controllerContext.Controller)
.Create(parameters).Capture(controllerContext);
return body;
}
// Using code from here:
// http://blog.approache.com/2010/11/render-any-aspnet-mvc-actionresult-to.html
public class ResponseCapture : IDisposable
{
private readonly HttpResponseBase response;
private readonly TextWriter originalWriter;
private StringWriter localWriter;
public ResponseCapture(HttpResponseBase response)
{
this.response = response;
originalWriter = response.Output;
localWriter = new StringWriter();
response.Output = localWriter;
}
public override string ToString()
{
localWriter.Flush();
return localWriter.ToString();
}
public void Dispose()
{
if (localWriter != null)
{
localWriter.Dispose();
localWriter = null;
response.Output = originalWriter;
}
}
}
public static class ActionResultExtensions
{
public static string Capture(this ActionResult result, ControllerContext controllerContext)
{
using (var it = new ResponseCapture(controllerContext.RequestContext.HttpContext.Response))
{
result.ExecuteResult(controllerContext);
return it.ToString();
}
}
}

Resources