I am trying to retrieve a resource from my asp .net restful service from an android client.
I have a MessagesController which has the method GetMessages:
[Authorize]
public IQueryable<Message> GetMessages()
{
return db.Messages;
}
To access this I have sent a request to /token and have obtained a key which I use from the client application to access the resource.
The trouble I have is that the client is receiving a 302 http error when trying to access the resource.
This is the method in the android client:
public void setAllSendersAndAllMessages()
{
String url = "Messages/GetMessages";
showpDialog();
String Url = baseUrl + url;
JsonArrayRequest req = new JsonArrayRequest(Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
allSenders = new String[response.length()];
allMessages = new String[response.length()];
for (int i = 0; i < response.length(); i++) {
JSONObject message = (JSONObject) response.get(i);
allSenders[i] = message.getString("sender");
allMessages[i] = message.getString("messageContent");
}
setInitialViews();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(context,error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "bearer "+ token);
return headers;
}
};
mRequestQueue.add(req);
}
I am overriding the getHeaders() method to send the authorization token to the service. This key and header works perfectly when using 'Postman' but fails in the android client for some unknown reason.
If anyone can offer some advice it would be greatly appreciated!
HTTP 302 is URL error, URL must be like :
http://server/WepApi/api/orders
Server : Your IIS server Name , or Your server IP address
Related
I'm using Android studio with Nodejs. To get data, I want to get Json from nodejs server using 'volley' At server( Nodejs, Express) delivery Tow JSon
res.write(JSON.stringify(results));
res.write(JSON.stringify(hot));
i want to get these Jsons from server to Android but fail... i can get only one JSON which is delivered first , this one
res.write(JSON.stringify(results));
how can i get two JSON ?? without merge JSON
public void onButton1Clicked(View v){
String url=editText.getText().toString();
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
println(response);
JSONArray jarray= new JSONArray(response);
for(int i=0;i<jarray.length();i++)
{
JSONObject Jobs=jarray.getJSONObject(i);
String title=Jobs.getString("title");
String content=Jobs.getString("content");
println(" title : " + title);
println(" content : " + content);
}
} catch (Exception e) {
println("에러남!");
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
println("error!###");
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<>();
return params;
}
};
request.setShouldCache(false);
Volley.newRequestQueue(this).add(request);
println("웹 서버에 요청함 : "+url);
}
I had 2 pages: first one is login page and second is category page. In login API after entering the credentials, I am getting the response as sesssion id from response header.
The sesssion id will be saved and it will use for further API calls. I am trying to call second API (category page). In this page, as an input am passing the saved session id in the request header. Getting response as "session expired". Also tried to pass Set-Cookie: PHPSESSID=d9f9sdkfjs9 in the request header. but it didn't work.
Note :
I am experiencing this issue in production environment only (SSL included)
I am using volley library for handling APIs.
public void fnCallLoginAPI() {
try {
//DEMO URL
//final String URL="http://demo.io/api/api.php?m=login";
//LIVE URL
final String URL = "https://www.live.com/shop/api/api.php?m=login";
final String requestBody = "email=abc.b#xyz.com" + "&password=43443==" + "&strPlatform=i" + "&strDeviceToken=null";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "PHPSESSID=" + sessionID);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
System.out.println("THE REQIEST BODY IS" + requestBody);
body = requestBody.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {
}
}
public void fnCallCateGoryAPI(){
try { final String URL ="https://www.live.com/shop/api/api.php?m=getcategories";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(strResponse);
sessionID = jsonObj.optString("session_id");
System.out.print("sessionID" + sessionID);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {}
}}
#fazil try after increasing the token expiration time from the backend
#fazil : I was facing something similar in my projects too and the reason i understood was actually due to multiple header values set under same key "Set-Cookie".
Please do check this in your logs.
Also, make sure that you have set the headers properly in your request(check the logs of request and response from your Server).
If everything implemented is correct and the issue is due to multiple values in the same header you need to check this implementation of volley : https://github.com/georgiecasey/android-volley-duplicateheadersfix
I am calling SAP's oData Service using Volley API from Android and getting HTTP 403 Error for the Request.POST. But for the Request.GET for another Service program is working fine. May I know if there is any issue with my code calling oData Service.
Iam passing MYSAPSSO2 token and CSRF Token obtained from my first request call. But getting Authentication error. Any idea what is missing here?
Same oData POST service using JQUERY/SAPUI5 is working fine without any issues.
try {
/** json object parameter**/
JSONObject jsonObject = new JSONObject();
jsonObject.put("SO", so);
jsonObject.put("STATUS", status);
jsonObject.put("NET_VALUE", amount);
Log.i("XXXX", thisMethod+"jsonObject params"+ jsonObject.toString() + "");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonRespObj) {
Log.i("XXXX", thisMethod+"Response from notification service: " + jsonRespObj.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.i("XXXXX", thisMethod+"Error Response: " + volleyError);
volleyError.printStackTrace();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
if (mysapsso2 != null) {
Log.i("XXX", thisMethod+"MYSAPSSO2 is : " + TokenHandler.getMYSAPSSO2Token());
Log.i("XXXX", thisMethod+"X-CSRF-Token is : " + TokenHandler.getCSRFToken());
params.put("Cookie", ServiceClass.mysapsso2);
params.put("X-CSRF-Token", TokenHandler.getCSRFToken());
params.put("contentType", "application/json");
}
return params;
}
};
queue.add(jsonObjectRequest);
} catch (JSONException e) {
Log.e("XXX", thisMethod+"There was an error => " + e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
Log.e("XXXX", thisMethod+"There was an error => " + e.getMessage());
e.printStackTrace();
}
Use StringRequest insted of JsonObjectRequest. Get json encoded response to a string & create json object. Below code work fine for me. try it.
public void getPostJsonData() {
final String URL = "URL";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("server_response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject JO = jsonArray.getJSONObject(i);
fname = JO.getString("firstname"); //or JO.toString()
lname = JO.getString("lastname");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityName.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Cookie", ServiceClass.mysapsso2.toString);
hashMap.put("X-CSRF-Token", TokenHandler.getCSRFToken().toString);
hashMap.put("contentType", "application/json");
return hashMap;
}
};
final RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<Object>() {
#Override
public void onRequestFinished(Request<Object> request) {
requestQueue.getCache().clear();
}
});
}
I'm trying to connect to live server using volley authentication and sending values through POST method. It worked well when connected to local server but I'm getting the below exception when connecting to live server.
BasicNetwork.performRequest: Unexpected response code 500 for "URL"
And server side error is below
Error parsing media type 'application/json; charset=utf-8, application/x-www-form-urlencoded; charset=UTF-8' Expected separator ';' instead of ',' This is the error getting in server side
Here is my code
public void userLogin(){
showDialog(DIALOG_LOADING);
final String json = new Gson().toJson(arr);
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
Const.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LOGIN Response :" + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
System.out.println("NetworkResponse "+ networkResponse);
if (networkResponse!= null && networkResponse.statusCode == 401) {
Login.this.runOnUiThread(new Runnable() {
public void run() {
invalidemail.setVisibility(View.GONE);
inactiveaccount.setVisibility(View.VISIBLE);
}
});
}
error.printStackTrace();
removeDialog(DIALOG_LOADING);
toast_tv.setText("There is no Internet connection. Try again...!");
toast.show();
}
}){
#Override
public byte[] getBody() {
try {
return json == null ? null : json.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
json, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String credentials = String.format("%s:%s",Const.auth_username,Const.auth_password);
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(),
Base64.NO_WRAP);
headers.put("Authorization", auth);
headers.put("Content-Type", "application/json; charset=utf-8");
return headers ;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(20 * DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 0, 0));
Volley.newRequestQueue(this).add(jsonObjReq);
}
On the server side Jersey is being used with Java.
Finally I fixed the issue.. Actually nothing wrong in code but the volley version which i used was deprecated. When updating the volley library it worked for me.
I am following using https://gist.github.com/itsalif/6149365 library for making XML requests.
It uses Simple-XML for serialising XML to Objects.
I am able to make XML request successfully when there is no header and parameters associate with the SOAP api. However I am unable get response while performing little complex request which consist of header and parameters.
My request format looks like this
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.holidaywebservice.com/HolidayService_v2/">
<SOAP-ENV:Body>
<ns1:GetHolidaysAvailable>
<ns1:countryCode>UnitedStates</ns1:countryCode>
</ns1:GetHolidaysAvailable>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Code
HashMap<String, String> mapData = new HashMap<>();
final String mRequestBody = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://www.holidaywebservice.com/HolidayService_v2/\">\n" +
" <SOAP-ENV:Body>\n" +
" <ns1:GetHolidaysAvailable>\n" +
" <ns1:countryCode>UnitedStates</ns1:countryCode>\n" +
" </ns1:GetHolidaysAvailable>\n" +
" </SOAP-ENV:Body>\n" +
"</SOAP-ENV:Envelope>";
SimpleXmlRequest dellaRequest = new SimpleXmlRequest<String>
(Request.Method.POST, "http://www.holidaywebservice.com//HolidayService_v2/HolidayService2.asmx?wsdl", String.class, headerDataMap, bodyDataMap,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("BaseActivity", "response = " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("BaseActivity", "Error:" + error.getMessage());
}
}
){
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, "utf-8");
return null;
}
}
};
I am getting 400 response code i.e. BAD REQUEST, state that invalid input is provided e.g validation error or missing data.
This api working fine in Postman rest client. So I am not able to figure out what am I doing wrong.
You can use Volley to call this XML request effectively.
String url = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx";
//Volley request
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
}) {
#Override
public String getBodyContentType() {
// set body content type
return "text/xml; charset=UTF-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return reqXML.getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
// TODO consider if some other action should be taken
return null;
}
}
};
//
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(request);