How to send and retrieve data to and from a website? - java

Ok, guys, so I'm recently developing android app that takes user's ID to login to website and fetch the data to my phone.
Now, there is login page: http://14.140.201.189:8280/opac/myaccount/myAccount.html
I want to send get and post request and retrieve data corresponding to a username and display it in my style in my android app.I don't want to use WebView for loading the whole web page, as the webpage is not reactive so all components are not at place.
Have you got any thoughts or tips/methods/guides/anything how to do that?

You can't use html page as API.
You need an API(php etc.) which will return data in JSON/XML form not in HTML or any other code like JS.
Parse it in your app and do what you want.

You can use simple volley API to make request and gather information from database. Get username and password from edittext. Pass to the function give below. Declare necessary all types of variables. Write simple php script for login. This is very simple and basic code.
/*************** PASS YOUR USERNAME AND PASSWORD TO FUNCTION *******************/
public void userValidationInfo(String username, String password){
String url = "url goes here"; // example.com/login.php
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
String user_id,user_type,
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
JSONObject obj;
try {
/***************** GET INFORMATION FROM REQUEST HERE ************************/
obj = dataArray.getJSONObject(0);
user_id = obj.getString(TAG_USER_ID);
user_type = obj.getString(TAG_USER_TYPE);
//Toast.makeText(getActivity(), brand_names, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
/***************** SET YOUR USER INFO HERE ****************/
Log.e(TAG, "onResponse: "+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/****************** SHOW WAITING MESSAGE / ERROR MESSAGE HERE *****************/
Toast.makeText(getContext(), "Taking bit longer ...", Toast.LENGTH_LONG).show();
}
}){
/******************** POST YOUR PARAMETERS HERE *************************/
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
queue1.add(stringRequest);
}
For more information check this gist.

Related

API Call in Android Studio using volley (JAVA)

I am not sure what I am doing wrong. I am very new to this and just jumped straight into trying to make API calls. I am trying to retrieve information from rapidAPI for a simple project I am working on to view prices of stocks and so on. I am using the volley package from Android Studio to make my APIcalls to retrieve JSON and trying to put that into a textView. The way I imagine this to work is that I press a button and then once that is clicked, it runs the code to get the information and then shows the response in the textView. however, when the button is clicked, nothing happens. no error or response of any sort.
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult= findViewById(R.id.text_view_result);
Button buttonParse= findViewById(R.id.button_parse);
mQueue= Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
jsonParse();
}
});
}
private void jsonParse(){
String url="https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/get-quotes?region=CA&lang=en&symbols=VEQT.TO";
JsonObjectRequest request= new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("result");
JSONObject result=jsonArray.getJSONObject(0);
int marketPrice= result.getInt("regularMarketPrice");
mTextViewResult.setText(String.valueOf(marketPrice));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextViewResult.setText("" +error.toString());
}
}){
#Override
public Map<String,String> getHeaders() throws AuthFailureError{
Map<String,String> params= new HashMap<>();
params.put("x-rapidapi-host", "apidojo-yahoo-finance-v1.p.rapidapi.com");
params.put("x-rapidapi-key", "APIKEY");
return params;
}
};
mQueue.add(request);
}
}
From what you've posted are you sure your x-rapidapi-key is APIKEY. Pretty sure that's the primary reason of your issue. Only after you put a valid API key in your request header, will your API call return a proper expected response.
You can read how to generate the rapidapi key from their official docs here
Currently the response you receive on api call using the wrong apikey is something like this:
{
"message": "Key doesn't exists"
}
Now in your java code you are looking for a JSONArray based on the key "result", while the response currently only has "message" being returned. That's the reason nothing happens, you can try finding the value in response for message and get the error messages if you wish. Generate a valid rapidapi key and try again, Good luck!

How to find specific data from a Volley Api string response

I am new to APIs and finally figured out how to successfully retrieve a request response from a website. The thing is I am completely lost on how I should handle the response. I don't know how to access certain values within the response
here is my API Volley code
RequestQueue requestQueue = Volley.newRequestQueue(this);
String uri = Uri.parse("https://chicken-coop.p.rapidapi.com/games/Fortnite?platform=pc")
.buildUpon()
.build().toString();
StringRequest stringRequest = new StringRequest(
Request.Method.GET, uri, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
displayResults.setText("Response: " + response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
displayResults.setText( "" + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("X-RapidAPI-Key", "5cdb2bbe57mshd9242c8d3177cb3p16f2fbjsnd7c5829eb4ad");
params.put("X-RapidAPI-Host", "chicken-coop.p.rapidapi.com");
return params;
}
};
requestQueue.add(stringRequest);
Here is the response query that I received
"result":{10 items
"title":"Fortnite"
"releaseDate":"Jul 25, 2017"
"description":"Epic Games next project has you building forts and stopping a zombie invasion."
"genre":[...
]6 items
"image":"https://static.metacritic.com/images/products/games/5/c7eb46ceb7da9c72c5a95193e8621faf-98.jpg"
"score":81
"developer":"Epic Games"
"publisher":[...
]1 item
"rating":"T"
"alsoAvailableOn":[6 items
0:
"iPhone/iPad"
1:
"PlayStation 3"
2:
"PlayStation 4"
3:
"Switch"
4:
"Xbox 360"
5:
"Xbox One"
How would I go about finding an explicit value from the response query? I have been searching for how to do this online and there are so many different ways to go about and I have no clue what to do. For example, how would I be able to put the Release Date into its own text box? Most of the examples I see online use JsonObjects when I m using a string response
in your onResponse method you need to parse your result so you can extract any data you want
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
// toaccess to your json data
String title = jsonArray.getString("title");
// your code
} catch (JSONException e) {
e.printStackTrace();
}
}

WearOS cannot make Volley request to an endpoint running on my computer's localhost

Problem
I'm attempting to make a simple POST JsonObjectRequest from a Huawei Watch and I keep getting com.android.volley.TimeoutError. I can successfully make other POST JsonObjectRequests from the watch to a different endpoint (not on my computer's localhost) and I can successfully make requests to the desired endpoint from a laptop.
What I've Tried:
Most posts suggest that this error is due to a bad connection or an incorrect endpoint. I tried increasing the timeout period to see if my connection was just slow but this did not fix things. The endpoint is definitely correct as it works when I make the request from a laptop.
I read on several posts that there are issues when connecting to unknown certificates. I followed the quick fix outline here: https://newfivefour.com/android-trust-all-ssl-certificates.html but this made no difference
My Code
mRequestQueue.add(volleyRequest());
...
private JsonObjectRequest volleyRequest(){
JSONObject data = null;
try{
data = new JSONObject("{'some':'data','other':'data'}");
} catch (JSONException e){
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(POST, mPath, data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("Volley Response", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Authorization", mToken);
return headers;
}
};
return request;
}

Android: Error connecting Android app with Database using php and json

My android app needs to send a string, and based on that, needs to get a response from the database.
I have a php that receives the string from the app, queries the database, and returns the response using echo json_encode($response_array); which works fine on the browser and echoes in a json object format.
However, In the app, I am using Volley. The php array $response_array above sends multiple strings which i need to display in the app textview.
I have set up volley in the gradle dependencies.
However, on running the app from my phone (which is connected on my laptop hotspot), the error i get is "null". This is the sample code from the app.
TextView o,t;
private RequestQueue requestQueue;
private static final String URL = "http://172.25.33.189/fadapp/mirror.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
o=(TextView)findViewById(R.id.tryOne);
t=(TextView)findViewById(R.id.tryTwo);
requestQueue = Volley.newRequestQueue(this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
if (jsonobject.names().get(0).equals("name")) {
o.setText(jsonobject.getString("name"));
if(jsonobject.getString("stat").equals("1")) {
t.setText(R.string.inText);
t.setTextColor(Color.parseColor("#00FF00"));
} else {
t.setText(R.string.outText);
t.setTextColor(Color.parseColor("#FF0000"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();;
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("speid", "database query string here");
return hashMap;
}
};
requestQueue.add(request);
Have you grant the intenet access to the app with ?
If you are hosting from your laptop you may need to open the port 80, to be sure that the problem isn't yor Volley set-up try to query for example google and print the response that should be a 200 http code

Volley GET JsonObjectRequest with JSONObjectParameter doesn't work at all

I've got a problem with Volley request - I want to send GET (another similiar POST also) request with JSONObject param (user having password and login) to authorize user and send back full user data. Although I can see during debugging that mRequestBody is correct JSON but I cannot receive it by my controller -
private void processLogin() throws JSONException {
this.user.setLogin(this.loginText.getText().toString());
this.user.setPassword(this.passwordText.getText().toString());
final JSONObject jsonObject = new JSONObject(new Gson().toJson(this.user));
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, UrlHelper.loginUrl, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
user = new Gson().fromJson(response.toString(), User.class);
if (user.getUserId().equals(getResources().getString(R.string.ERROR))) {
onLoginFailed();
} else {
onLoginSuccess(user);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
Controller method:
#RequestMapping(value = "/loginTest", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public User someMethod(#RequestBody User user) throws SQLException {
return userService.authenticateUser(user.getLogin(), user.getPassword());
}
Without annotation #RequestBody I it process but User in param is empty, so I process User with null password and login. Recently I did it by StringRequest Please, help me. :)
As a part of the HTTP specs, GET requests have no body. You can create and send GET requests with a body though, but that's meaningless since the body has no semantic meaning in the GET method specification. I don't know too much about Spring, but my guess is that Spring is probably ignoring the body of the request because it's a GET method. You should send and receive the request as POST if your intention is to put something inside the body.

Categories

Resources