I'm using Volley to download text files from a website.
This is the content of a sample text file:
NEON Wönn 30€ Kostüm größter Spaß
TESTTESTTESTTEST★★★★TESTTEST:::TEST
I put that in Notepad and selected 'Encoding UTF-8' in the SaveFileDialog.
In Filezilla in the server manager I selected 'Force UTF-8' before I uploaded the file.
When I download it with Volley the response will look like this:
NEON Wönn 30⬠Kostüm gröÃter SpaÃ
TESTTESTTESTTESTââââTESTTEST:::TEST
Here is my method:
public static void getRequest(String url) {
RequestQueue queue = Volley.newRequestQueue(activity);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response is gibberish :/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", error.toString());
}
});
stringRequest.setShouldCache(false);
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
Is there a way to fix that by forcing Volley to use UTF-8 Encoding?
I had to Override this method:
#Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
String strUTF8 = null;
try {
strUTF8 = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return Response.success(strUTF8,
HttpHeaderParser.parseCacheHeaders(response));
}
I'm working with a server (that I do not control) that sends back UTF-8 responses without setting charset in the content-type header. Volley currently defaults to ISO-8859-1 in this case.
I simply wanted to change the default charset without forcing every response to UTF-8. I ended up just using parseNetworkResponse() to intercept Volley's response processing and check to see if charset is missing from the response headers. If it is missing, I force it to look like the server said "charset=UTF-8" and then just let the normal processing continue.
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// Volley's default charset is "ISO-8859-1". If no charset is specified, we want to default to UTF-8.
String charset = HttpHeaderParser.parseCharset(response.headers, null);
if (null == charset) {
String contentType = response.headers.get("Content-Type");
contentType = (null != contentType) ? (contentType + ";charset=UTF-8") : "charset=UTF-8";
response.headers.put("Content-Type", contentType);
}
return super.parseNetworkResponse(response);
}
Related
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 have array look like this
arrayname[{"code" : "abc","code2":"cba",}]
i want send it as paramaters,put it in getParam() function with volley to my server
the problem look similiar to this
Volley pass array as parameters
any help how to do it?
thanks in advance
Here is a method in an app I made that does what you're trying to do. (I think?)
My problem was that I had multiple post parameters that I wanted to send, but one of them was an array.
For example:
http://www.yourDB.com/getData.php?param1=blah¶m2=blah¶m3=[ [array] ].
So... to make sure that the PHP page understands that I'm sending an array, I add data to the array as follows (notice the ' [] ' following the param).
postParams.add(new String[]{"param3[]", itemName});
So... the server sees this:
http://www.yourDB.com/getData.php?param1=blah¶m2=blah¶m3[]=item1¶m3[]=item2¶m3[]=item3...
The key to understand is this part:
"#Override
public byte[] getBody() throws AuthFailureError {"
The trick is that you send an ArrayList of String arrays into the method and override the getBody() part like this:
private void Url_2_Adapter(String url, final ArrayList<String[]> postParams) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.i(TAG, "WE HAD ERROR " + error.toString());
try {
Toast.makeText(getActivity(), "Server says: Error code " + error.networkResponse.statusCode + "\nIf this continues, please report it! Thanks.", Toast.LENGTH_LONG).show();
}
catch (Exception e){
}
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
StringBuilder result = new StringBuilder();
boolean first = true;
for (String[] entry : postParams)
{
if (first) {
first = false;
} else {
result.append("&");
}
try {
result.append(URLEncoder.encode(entry[0], "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
// this basically will never happen :)
}
}
return result.toString().getBytes();
}
};
Z_VolleySingleton.getInstance().getRequestQueue().add(stringRequest);
}
For this, you have to make JsonArrayRequest. In Volley there is JsonArrayRequest class use that one for JsonArray request.
This is the method available in JsonArrayRequest class.
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
May be this will help you:
JSONArray jArrayInput=new JSONArray();
JSONObject jObjectInput=new JSONObject();
jObjectInput.put("code", abc);
jObjectInput.put("code2", cba);
jArrayInput.put(jObjectInput);
JsonArrayRequest request = new JsonArrayRequest(Method.POST, /*Your base url*/, jArrayInput , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Here success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Here error response
}
});
MyVolley.getRequestQueue().add(request);
I didn't worked on the Volley Library , I used AsyncHttpClient : The logic you can apply here like this:
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
jsonObject.put("code", abc);
jsonObject.put("code2", cba);
jsonArray.put(jsonObject);// this you need to pass using volley library
I'm using Volley as my http client library.
i need to send payload raw data as part of the request with Volley?
there are posts like: How to send Request payload to REST API in java?
but how this can be achieved using Volley?
need to use StringRequest as djodjo mentioned.
also getBody method need to be override - taken from here Android Volley POST string in body
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody="your body as string";
// usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
try {
httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+ URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
} catch (UnsupportedEncodingException exception) {
Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
return null;
}
return httpPostBody.getBytes();
}
example:
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
check the source and more info here
**UPDATE: ** If you need to add params you can simply override getParams()
Example:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "val1");
params.put("randomFieldFilledWithAwkwardCharacters","{{%stuffToBe Escaped/");
return params;
}
You don't need to override getBody yourself neither encode special chars as Volley is doing this for you.
I just want to check whethere the user entered url is valid or not so far what i have tried is HTTPurl connection am getting the result but response time is very slow how to make it speed up let me post my code :
public Boolean Netwrok(String str) {
HttpURLConnection connection = null;
try {
URL myUrl = new URL(str);
connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
InputStream response = connection.getInputStream();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
connection.disconnect();
}
}
This is what am trying now am trying to make it with volley am getting response but don't know how to validate it can anybody helpmeout:
Let me post my volley code:
RequestQueue queue = Volley.newRequestQueue(getContext());
String str_url = getEditText().getText().toString();
str_url = s;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Intent intent = new Intent(getContext(), LoginActivity.class);
getContext().startActivity(intent);
// mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
setDialogMessage("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
can anybody tell any solution for my prob
Android has pre-build Patterns for WEB_URL which you can use as:-
if (Patterns.WEB_URL.matcher(serverURL).matches() == false){
//Invalid
}else{
//valid
//In here you can also put one more check by opening connection to URL and check for HTTP_RESPONSE_OK (200) then url is FINE.
}
try below way, just change code in onErrorResponse method of volley request
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//setDialogMessage("That didn't work!");
// NOT VALID URL
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse.statusCode != 200) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
//code 404: for page not found, you can read about more responce code in link below
}
}
});
more about http status code
I am currently using OkHttp, but I'd like to switch to Volley.
Maybe it is the late hour, but I can't seem to figure out how to send a POST request with just text in the body (in my app, the body is encrypted as a whole and then decrypted on the server side, and then split into params).
Also, my response should be a binary (not an image) that I'd like to save to a file.
I'm beginning to think that Volley isn't my best solution.
Help would be much appreciated.
Use getParams to add body in POSt, like here
url = "http://google.com";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error response
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("param1", "aaa");
params.put("param2", "bbb");
return params;
}
};
queue.add(postRequest);
Volley is not designed for sending/receiving big data and multipart request. Best would be to have data in response base64 encoded.
Volley offers a method getBody() which you can use to put any data into the HTTP request body:
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
body = mContent.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unable to gets bytes from content", e.fillInStackTrace());
}
return body;
}