Post string request volley? - json

I want to POST the following string to a server and receive a JSONObject via android volley! The documentation says the request to the server should be in the format given below, with Content-Type as "application/x-www-form-urlencoded". How do I make this request with volley?
{
Username=usr&Password=passwd&grant_type=passwd
}
Thanks in advance!

First you should Override your getbody() and in that function encode your parameteres... for example:
#Override
public byte[] getBody() {
Map<String, String> params = new HashMap<String, String>();
params.put("password", "yourpassword");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
protected byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
this the way to encode your parameters.... volley actually has implemented the following function, and it works, for me it works... hope this help you.

So your question is confusing. POST body parameters aren't encoded inside a JSON body.
I haven't tested it but if you understand HTTP you should understand the rest from here.
final Map<String, String> postBody = new HashMap<String, String>();
postBody.put("Username", "usr");
postBody.put("Password", "passwd");
postBody.put("grant_type", "passwd");
final Listener<JSONObject> responseListener = ...;
Request request = new Request<JSONObject>(Method.POST, "http://example.com", errorListener) {
void deliverResponse(JSONObject obj) {
responseListener.onResponse(obj);
}
protected Map<String, String> getPostParams() throws AuthFailureError {
return postBody;
}
protected Response<T> parseNetworkResponse(NetworkResponse response) {
if (response.status == 200) {
JSONObject responseBody = new JSONObject(new String(response.data));
return Response.success(body, getCacheEntry());
} else {
return new Response<JSONObject>(new VolleyError(response);
}
}
};
requestQueue.add(request);

Related

How to add attachment using TestRail API?

public static void fnUpdateResultToTestRail(String trusername, String trpassword, String trRunId,String testCaseName,String status, String testStepDetails)
throws MalformedURLException, IOException, APIException {
APIClient client = new APIClient("testrailurl");
client.setUser("username");
client.setPassword("password");
HashMap data = new HashMap();
data.put("status_id", status);
data.put("comment", testStepDetails);
HashMap data1 = new HashMap();
data1.put("attachment","C:\\Pictures\\\\X-SecurityToken-Issue.jpg";
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId);
//System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString();
if (testrailTestCaseName.equals(testCaseName)) {
System.out.println(c.get("id"));
client.sendPost("add_result/" + c.get("id"), data);
client.sendPost("add_attachment_to_case/"+c.get("case_id"), data1);
break;
}
}
}
TestRail API returned HTTP 400("No file attached or upload size was exceeded.")
As per document, we need to pass Headers: { "Content-Type","value":"multipart/form-data" }
API client has inbuilt methods....
public Object sendPost(String uri, Object data)
throws MalformedURLException, IOException, APIException
{
return this.sendRequest("POST", uri, data);
}
private Object sendRequest(String method, String uri, Object data)
throws MalformedURLException, IOException, APIException
{
URL url = new URL(this.m_url + uri);
...........
}
How to add the header in this inbuilt method on run time..?
Can any one help on this?

How to parse JSON and urlencoded responses with Jetty HttpClient?

Please recommend the optimal approach for parsing urlencoded or JSON-encoded responses when using Jetty HttpClient.
For example, I have created the following utility class for sending ADM-messages and use BufferingResponseListener there, with UrlEncoded.decodeUtf8To​ (for parsing bearer token response) and JSON.parse (for parsing message sending response):
private final HttpClient mHttpClient;
private final String mTokenRequest;
private String mAccessToken;
private long mExpiresIn;
public Adm(HttpClient httpClient) {
mHttpClient = httpClient;
MultiMap<String> params = new MultiMap<>();
params.add("grant_type", "client_credentials");
params.add("scope", "messaging:push");
params.add("client_id", "amzn1.application-oa2-client.XXXXX");
params.add("client_secret", "XXXXX");
mTokenRequest = UrlEncoded.encode(params, null, false);
}
private final BufferingResponseListener mMessageListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
if (result.getResponse().getStatus() % 100 == 4) {
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
Map<String, String> resp = (Map<String, String>) JSON.parse(jsonStr);
String reason = resp.get("reason");
if ("AccessTokenExpired".equals(reason)) {
postToken();
} else if ("Unregistered".equals(reason)) {
// delete the invalid ADM registration id from the database
}
}
return;
}
String jsonStr = getContentAsString(StandardCharsets.UTF_8);
Map<String, String> resp = (Map<String, String>) JSON.parse(jsonStr);
String oldRegistrationId = (String) result.getRequest().getAttributes().get("registrationID");
String newRegistrationId = resp.get("registrationID");
if (newRegistrationId != null && !newRegistrationId.equals(oldRegistrationId)) {
// update the changed ADM registration id in the database
}
}
};
private final BufferingResponseListener mTokenListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (result.isSucceeded()) {
String urlencodedStr = getContentAsString(StandardCharsets.UTF_8);
MultiMap<String> params = new MultiMap<>();
UrlEncoded.decodeUtf8To(urlencodedStr, params);
long now = System.currentTimeMillis() / 1000;
mExpiresIn = now + Long.parseLong(params.getString("expires_in"));
mAccessToken = params.getString("access_token");
}
}
};
public void postMessage(String registrationId, int uid, String jsonStr) {
long now = System.currentTimeMillis() / 1000;
if (mAccessToken == null || mAccessToken.length() < 32 || mExpiresIn < now) {
postToken();
return;
}
mHttpClient.POST(String.format("https://api.amazon.com/messaging/registrations/%1$s/messages", registrationId))
.header(HttpHeader.ACCEPT, "application/json")
.header(HttpHeader.CONTENT_TYPE, "application/json")
.header(HttpHeader.AUTHORIZATION, "Bearer " + mAccessToken)
.header("X-Amzn-Type-Version", "com.amazon.device.messaging.ADMMessage#1.0")
.header("X-Amzn-Accept-Type", "com.amazon.device.messaging.ADMSendResult#1.0")
.attribute("registrationID", registrationId)
.content(new StringContentProvider(jsonStr))
.send(mMessageListener);
}
private void postToken() {
mHttpClient.POST("https://api.amazon.com/auth/O2/token")
.header(HttpHeader.ACCEPT, "application/json")
.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded")
.content(new StringContentProvider(mTokenRequest))
.send(mTokenListener);
}
The above class works okay, but seeing that there are Jetty-methods with InputStream in arguments, like
UrlEncoded.decodeTo​(java.io.InputStream in, MultiMap map, java.lang.String charset, int maxLength, int maxKeys)
and
JSON.parse​(java.io.InputStream in)
I wonder if there is a smarter way to fetch and parse... maybe with something more effective than BufferingResponseListener?
In other words my question is please:
How to use the "streaming" version of the above parsing methods with HttpClient?

Android Volley POST body request recieved EMPTY at backend

i'm using the following code to post a json object to php server :
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("tag", "jsonParams");
JSONObject jsonObject = new JSONObject(paramsMap);
Log.d("JSON", jsonObject.toString());
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("JSON RESPONSE", response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON ERROR", error.getMessage());
}
});
requestQ.add(jsonRequest);
and using this to receive the object in php:
$body = '';
$handle = fopen('php://input','r');
while(!feof($handle)){
$body .= fread($handle,1024);
}
$logger->log("login request","request body: ".$body);
the problem is that the $body is always empty i used FIDDLER to check my HTTP request and it's there as raw data like this : {"tag":"jsonParams"}
so what am i messing ?
thx in advance.
I know this is an old question, but for future readers...
I have solved the exact same problem by using StringRequest instead of JsonObjectRequest. The constructor differs just very slightly and you can then easily parse string response to JsonObject like this:
JSONObject response = new JSONObject(responseString);
Not sure what was your problem, but for the future googlers:
My problem was that I wasn't reading from php://input
Full code (working):
Java:
JSONObject jsonobj; // declared locally so that it destroys after serving its purpose
jsonobj = new JSONObject();
try {
// adding some keys
jsonobj.put("new key", Math.random());
jsonobj.put("weburl", "hashincludetechnology.com");
// lets add some headers (nested JSON object)
JSONObject header = new JSONObject();
header.put("devicemodel", android.os.Build.MODEL); // Device model
header.put("deviceVersion", android.os.Build.VERSION.RELEASE); // Device OS version
header.put("language", Locale.getDefault().getISO3Language()); // Language
jsonobj.put("header", header);
// Display the contents of the JSON objects
display.setText(jsonobj.toString(2));
} catch (JSONException ex) {
display.setText("Error Occurred while building JSON");
ex.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("onResponse()");
try {
result.setText("Response: " + response.toString(2))
System.out.println("Response: " + response.toString(2));
} catch (JSONException e) {
display.setText("Error Occurred while building JSON");
e.printStackTrace();
}
//to make sure it works backwards as well
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("onErrorResponse()");
System.out.println(error.toString());
}
});
System.out.println("After the request is made");
// Add the request to the RequestQueue.
queue.add(jsObjRequest);
Clarification: display and result are two TextView objects I am using to display data on the screen, and queue is Volley's request queue.
PHP:
$inp = json_decode(file_get_contents('php://input')); //$input now contains the jsonobj
echo json_encode(["foo"=>"bar","input"=>$inp]); //to make sure we received the json and to test the response handling
Your Android Monitor should output sth. like :
{
"foo":"bar",
"input":{
"new key":0.8523024722406781,
"weburl":"hashincludetechnology.com",
"header": {
"devicemodel":"Android SDK built for x86",
"deviceVersion":"7.1",
"language":"eng"
}
}
}

Json parsing Using Volley does not get cahced

I Parse json using volley framework, which every time gets response from the server, does not check the cache, It has taken a whole day, Here is my code. Any of you have used volley for parsing json are expected to help
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(diag_url);
if(entry != null){
try {
String data = new String(entry.data, "UTF-8");
// handle data, like converting it to xml, json, bitmap etc.,
// Parsing json
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
try {
DiagRegPojo test = new DiagRegPojo();
JSONObject obj = jsonArray.getJSONObject(i);
String testName = obj.getString("content");
Log.d("Response From Cache", testName);
test.setTitle(testName);
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
// Creating volley request obj
JsonArrayRequest testReq = new JsonArrayRequest(diag_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
DiagRegPojo test = new DiagRegPojo();
test.setTitle(obj.getString("content"));
Log.d("Response From Server", obj.getString("content"));
// adding movie to movies array
testList.add(test);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
})
{
//**
// Passing some request headers
//*
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Set-Cookie", MainActivity.sharedpreferences.getString(savedCookie, ""));
headers.put("Content-Type", "application/x-www-form-urlencoded");
//headers.put("Content-Type","application/json");
headers.put("Accept", "application/x-www-form-urlencoded");
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(testReq);
}
}
To cache images, I have used this. sure it can be of some help to you.
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
.
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}

Error : HTTP/1.1 302 Moved Temporarily

I am doing Http POST request using HTTPClient 4.2.2. I am using .pfx certificate to access the URL mentioned in post request. But I am getting 302, Move temporarily error
//Java Code
public class CertificateAuth {
private static final long TIMEOUT = 500000000L;
//set trust store to be used to trust server certificate
private String tokeApiPostUrl = "http://test.com/l1/rest1/lt/v1/data";
private String tokenPost = "{\"id\": \"Token_15555\",\"type\": \"token\",\"entity_type\": \"Store\",\"entity_id\": \"StoreId\",\"expiration_time\": 1376579410}";
//client is taken as class varibable so that Cookies set by Server persists between
//multiple calls
private HttpClient client = null;
public CertificateAuth() {
}
public String createToken() throws Exception {
// set reasonable timeouts as we seem to wait forever to get a response:
KeyStore keystore = KeyStore.getInstance("pkcs12");
InputStream keystoreInput = new FileInputStream("abc.pfx");
keystore.load(keystoreInput, "password".toCharArray());
SchemeRegistry schemeRegistry = new SchemeRegistry();
SSLSocketFactory lSchemeSocketFactory = new SSLSocketFactory(keystore, "qwerty10");
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", 443, lSchemeSocketFactory));
final HttpParams httpParams = new BasicHttpParams();
client = new DefaultHttpClient(new SingleClientConnManager(httpParams, schemeRegistry), httpParams);
String version = null;
HttpPost httpPost = new HttpPost(tokeApiPostUrl);
// httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
try {
Map<String, String> headersParameters = new HashMap<String, String>();
JSONObject jsonObj = new JSONObject(tokenPost);
setParametersJson(httpPost, headersParameters, jsonObj);
HttpResponse resp = client.execute(httpPost);
if(resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) {
System.out.println("Succesfully queried");
}
} finally {
httpPost.releaseConnection();
}
return version;
}
private void setParametersJson(HttpRequestBase httpOperation, Map <String, String> headerParameters, JSONObject jsonObject) {
for (String headerName : headerParameters.keySet()) {
httpOperation.setHeader(headerName, headerParameters.get(headerName));
}
if (jsonObject != null) {
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
if (httpOperation instanceof HttpPost) {
((HttpPost) httpOperation).setEntity(stringEntity);
} else if (httpOperation instanceof HttpPut) {
((HttpPut) httpOperation).setEntity(stringEntity);
}
} catch(UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
CertificateAuth ua = new CertificateAuth();
ua.createToken();
}
}
Add this line to your code.
client.setRedirectStrategy(new LaxRedirectStrategy());