I'm trying to perform a POST request using Volley, but I keep getting the error com.android.volley.NoConnectionError: java.net.UnknownHostException: Unable to resolve host "<my custom API URL>". No address associated with hostname. The request seems to work using Postman and I have already gave the necessary permissions in the Manifest (both INTERNET and ACCESS_NETWORK_STATE).
I'm using a local server with SequelPro and Laravel.
Here is the Postman working screens:
Postman body
Postman headers
Here is the part of the code of the Login Activity:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText emailInput = findViewById(R.id.emailInput);
final EditText passwordInput = findViewById(R.id.passwordInput);
final EditText confirmPasswordInput = findViewById(R.id.confirmPasswordInput);
final Button loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = emailInput.getText().toString();
final String password = passwordInput.getText().toString();
final String confirmPassword = confirmPasswordInput.getText().toString();
try {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://lalalaravel.test/api/login";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", email);
jsonBody.put("password", password);
jsonBody.put("password_confirmation", confirmPassword);
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("VOLLEY", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("VOLLEY", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM4MmM1OTc5YzFhN2Y1ZDczMjFjMWQwMThhYzBmMTdkZWI1MzlkMjIxN2M2YWRhMDUxNzhlMTcyNmVmOWQwZDM3ZGY2ZTdlNDIxOGUxNmQ5In0.eyJhdWQiOiIxIiwianRpIjoiMzgyYzU5NzljMWE3ZjVkNzMyMWMxZDAxOGFjMGYxN2RlYjUzOWQyMjE3YzZhZGEwNTE3OGUxNzI2ZWY5ZDBkMzdkZjZlN2U0MjE4ZTE2ZDkiLCJpYXQiOjE1MjkyNTg2OTAsIm5iZiI6MTUyOTI1ODY5MCwiZXhwIjoxNTYwNzk0NjkwLCJzdWIiOiIyMSIsInNjb3BlcyI6W119.hyjXMXwRb3GLVJ7w5KBmzwVDzoPcztjXKHOx8fqwN6jOvTfgki_HngAIB3JaG5Xhb7w8mFBX03fUDwzOc2S108SiBTjZ7B14GtYmlC8OgxVkKXcCqJ_0UOZBsgCYo7p7f4HBIgIyZ8StrsNlNbuj_4W5Pz2YY4WitbvDX9LsZFIbdz3vhVlmtR2zKA23hyRGUsWZniB7zLGEvsUt5XA9NNAy9XWySaw7JuRZ4uyYm0bXHrJKHSTmfBd9KOJSdpnWs_9miNvh5g_DJo39L7awAlG7-cb67Ih00bhrmgGAWp6VCEd5h-EhIc-l1qfYT56osDgnYIqMk3cAgIWrYrhrs6-mZ1miXqipk9dClliUO7DBylZW8cRbQ5PQ5xisE_wCMTSUr7VYE_7RyjMzDaZuctf8kHQ_W27ED9tq14NhgvJs4hkpO6Gzr32zyMj-KRan2Fc3O1CYgyJx0OR2LhvXrxp2PxfUSIzR8eGHOGypLicU_suG3Dsz_UG7Kp5EdhP8Ma9eDyWObfU64iFYZsuz58TOBOH2ssH7_PpKHBGmchxQSjpKsIwsjeYpdbVmzXG7cZe2_AOEZpXmlwkaAZLow3_kDPfvuoCIWVsEKfgRs72t3B8fIwSt-vWaXpGYKjGOjf9ZOXpiKjG1XHaur0vLR1eiIXKVFSyn6y42FIlbSqk");
headers.put("Content-Type", "application/json");
return headers;
}
};
queue.add(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
Honestly I don't know what to do, Internet is working fine and some of my classmates are doing their requests with iOs with no problem, it shouldn't be a connection problem...
Related
How to add the request body to my code like using Postman's body tab. I figure it out only request header. 
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.textView);
String url = "url";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("Response : ",response.toString());
textView.setText("Success!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response error : ",error.toString());
error.printStackTrace();
textView.setText("Failed!");
}
})
{
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("accept-language","EN");
headers.put("authorization","<autho>");
headers.put("requestUId","<requestID>");
headers.put("resourceOwnerId","<resorceOwnerID>");
return headers;
}
};
requestQueue.add(objectRequest);
}
}
Ref Postman's head tab :
https://s3.amazonaws.com/postman-static-getpostman-com/postman-docs/58960775.png
Thank you
Create your JSONObject request as below:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
Then the third parameter in the JsonObjectRequest() constructor is the request, you are currently passing null. Replace it with jsonBody.
Edit
You also have to change your HTTP method to POST instead of GET if you want your parameters to be sent in the request body.
i have a server side api method which accept Model class as a parameter
which does work fine i have checked it but from android i am confused how to send a Model class as a parameter?
public class Login extends AppCompatActivity {
EditText email, password;
String Email, Pass;
Button loginbtn;
String URL = "https://192.168.0.102/api/campaign/Logins";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
handleSSLHandshake();
email = findViewById(R.id.input_email);
password = findViewById(R.id.password);
loginbtn = findViewById(R.id.login_button);
final RequestQueue queue = Volley.newRequestQueue(this);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Email = email.getText().toString();
Pass = password.getText().toString();
StringRequest postRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("email", Email);
params.put("password", Pass);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
queue.add(postRequest);
}
});
This is what i have tried i know the problem is from the server side can anyone help me what i am thinking is the problem or is there anything else ?
You just need to add a JSONObject with the post parameters as key-value pairs in the JSON Object. Here is the example for you:
JSONObject postparams = new JSONObject();
postparams.put("keyX", "valueX")
postparams.put("KEY", "Value")
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
i trying to connect my project in android studio to Asp.net API
and i'm using Volley Lib to Get Json Request but he did'nt read the response
and I getting this massage in Log
((( E/Volley: [352] BasicNetwork.performRequest:
Unexpected response code 400 for http://10.10.4.150:61511/api/Feedback/30)))
-Api work correctly i`m test with postman
enter image description here
public static final String GET_BY_ID = "http://10.10.4.150:61511/api/Feedback/30";
EditText id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.idtxt);
}
public void click(View v) {
if (v.getId() == R.id.btnget) {
insertData (id.getText().toString()) ;
}
}
public void insertData (String value){
HashMap<String,String> param = new HashMap<String, String>();
param.put("id",value);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, GET_BY_ID,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
JSONObject ob = response.getJSONObject("userId") ;
int name = ob.getInt("userId");
Toast.makeText(getBaseContext(),name,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
I want to send push notification using firebase cloud messaging.
I have successfully stored access token in shared preference.
I am using Volley to send request to server but it(Volley) shows com.android.volley.Server error after sending the request.
Note: I am just sending firebase push notification on same device since the access token passed in body of request is of same(current) user
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String token= Helper.getAccessToken(this);
if(token!=null){
sendRequest();
}
}
private void sendRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url= "https://fcm.googleapis.com/fcm/send";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();//Here ServerError shows
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
String accessToken = Helper.getAccessToken(MainActivity.this);
params.put("to",accessToken);
params.put("title", "This is string message");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header = new HashMap<>();
header.put(""Authorization,"key=" + "Here is my server key");
header.put("Content-Type","application/json");
return header;
}
}
;
requestQueue.add(request);
}
It seems a little bit overkill just to make a simple POST operation. I think it would be better to use something like OkHTTP to carry out this operation. It should be a very straightforward POST operation
private void sendRequestByOk() {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject jsonData = new JSONObject();
try {
jsonData.put("body","Hi!! This is the message from device");
jsonData.put("title","dummy title");
json.put("notification",jsonData);
json.put("to",Helper.getAccessToken(MainActivity.this));
RequestBody body = RequestBody.create(JSON,json.toString());
okhttp3.Request request = new okhttp3.Request.Builder()
.header(AUTHORIZATION_KEY,AUTH_VALUE)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
okhttp3.Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
// Toast.makeText(MainActivity.this, finalResponse,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}.execute();
}
I think there is problem in below code:-
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params = new HashMap<>();
String accessToken = Helper.getAccessToken(MainActivity.this);
params.put("to",accessToken);
//change this
params.put("notification", "This is string message");
return params;
}
So I have this customer, and I want to update the fcm_token value in the customer object via post request using volley, but It's not working..!
See the json link >> http://www.mocky.io/v2/5911638a1200001e020fb5d2
My attempt so far..
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
);
requestQueue.add(jsObjRequest);
UPDATE
I change request to this and still didn't change..!?
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
UPDATE 2
so after a lot of attempts still not solved, but I'm gonna explain what I want to do exactly maybe you will get what I want to accomplish, I wanna send my device fcm token to server based on the user id when login, so I have a Customer model class that has the value of fcm_token it must after the request is made it must be set as my token, the process happens in web server btw.
Here's my code so far..
MyFirebaseInstanceIDService Class
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
String refreshedToken;
#Override
public void onTokenRefresh() {
refreshedToken = FirebaseInstanceId.getInstance().getToken();
Hawk.put("token", refreshedToken);
}
public static void sendRegistrationToServer(Context context) {
}
}
Customer Model Class
public class Customer {
#SerializedName("avatar_url")
#Expose
private String cusPicURL;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("fcm_token")
#Expose
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
// ..... more variables & setters and getters
My Request Code inside a repository class (all request are here..)
public static void UpdateFCM_Token(final Context context, final String token) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST,
URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject o = response.getJSONObject("customer");
Gson gson = new Gson();
Customer customer = gson.fromJson(o.toString(), Customer.class);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("FCM OnResponse", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("FCM Error: ", "" + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(req);
}
The fragment in MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// code..
String token = Hawk.get("token");
Log.i("TOKEN", token);
DriverRepository.UpdateFCM_Token(getActivity(), token);
return rootView;
}
The Logs
Hey you suppose to add Map + remove null from new JsonObjectRequest(.......null,listener....):
private void sendRegistrationToServer(String token) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
Customer me = Hawk.get("user");
String URL = API_URLs.TokenURL(me.getID());
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//Log
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> map = new HashMap();
//add your params here to the map
return map;
}
};
requestQueue.add(jsObjRequest);
You may have to override getParams of JsonObjectRequest and pass your POST params.
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method
.POST, URL, null, listener, errorListener){
protected Map<String,String> getParams() throws AuthFailureError{
return postParamsMap;
}
}
You can also use StringRequest instead of JsonObjectRequest.
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
//Converting the response to JSON
JSONObject jsonObj = new JSONObject(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("fcm_token", token);
return params;
}
};
requestQueue.add(jsonObjReq);
after some works, I solved it using okhttp3 since volley didn't work for me, although the rest of request in my app are using volley but this one is only okhttp3, I hope that's not a bad practice.
Thanks a lot guys for ur help..!
here's the code in my request method.. in case someone might have the same problem.
public static void UpdateFCM_Token(final String token) {
Customer me = Hawk.get("user");
Log.i("USER ID: ", "" + me.getID());
String URL = API_URLs.TokenURL(me.getID());
OkHttpClient client = new OkHttpClient();
String json = "{\"fcm_token\":\"" + token + "\"}";
Log.i("Json : ", json);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
okhttp3.Request request = new okhttp3.Request.Builder()
.url(URL)
.post(body)
.addHeader("content-type", "application/json")
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
isTokenSent = true;
Log.i("response ", response + "");
} catch (IOException e) {
e.printStackTrace();
Log.i("IOException", "" + e);
}
}