I have a method in spring and I want to access the method using Apache HttpClient.
following is my method :
#PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
#RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
public #ResponseBody
void createRequisition(#RequestBody CreateRequisitionRO[] request,
#RequestHeader("validateOnly") boolean validateOnly) {
logger.debug("Starting createRequisition()...");
for (int i = 0; i < request.length; i++) {
CreateRequisitionRO requisitionRequest = request[i];
// FIXME this has to be removed/moved
requisitionRequest.setFundManager(requisitionRequest.getUserId());
// FIXME might have to search using param level as well
SystemDefault sysDefault = dbFuncs.references.systemDefault
.findByCompanyAndDivisionAndPortfolio(
userContext.getCompany(),
userContext.getDivision(),
requisitionRequest.getPortfolio());
requisitionRequest.setCustodianN(sysDefault.getCustodianN());
gateKeeper.route(requisitionRequest);
}
}
And this is how I log in to the system and make the tomcat run where the application is deployed since the method uses other classes for some functionalities.
I was able to log in to the system without any issues through problematically but i get the following exception -- java.io.EOFException: No content to map to Object due to end of input
This is my main class :
package com.hexgen.reflection;
public class ReflectionWebAPITest {
public static void main(String[] args) {
HttpClientRequests httpRequest = new HttpClientRequests();
String uri="";
try {
uri = "http://localhost:8080/api/trade/createrequisition";
httpRequest.doSubmit("mayank", "hexgen",uri);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
this is my doSubmit Method :
public void doSubmit(String username, String password, String uri) {
HttpClient client = new DefaultHttpClient();
JsonConverter jsonROConverter = new JsonConverter();
CreateRequisitionRO[] request = new CreateRequisitionRO[1];
BigDecimal priceFrom= new BigDecimal("100000");
BigDecimal quantity= new BigDecimal("2");
request[0] = new CreateRequisitionRO();
request[0].setPortfolio("HEXGENFUND");
request[0].setTransSrlNo(new BigDecimal(1));
request[0].setTransCode("BUY");
request[0].setInvestReason("009");
request[0].setInflowOutflow(InflowOutflow.I);
request[0].setTradeDate(new LocalDate());
request[0].setTradeDate(new LocalDate());
request[0].setTradeDateUpto(new LocalDate());
request[0].setTradeTime("11:27:9");
request[0].setInvestCategory("FVTPL");
request[0].setCustodian("DEUTSCHE");
request[0].setHoldType("HOLD");
request[0].setSecurityType(SecurityType.INV);
request[0].setSecurity("DABU02");
request[0].setAssetClass("EQU");
request[0].setIssuer("DABU");
request[0].setMarketType(MarketType.MKT);
request[0].setTradePriceType("");
request[0].setRequisitionType(RequisitionType.SO);
request[0].setPriceFrom(priceFrom);
request[0].setPriceTo(priceFrom);
request[0].setMarketPrice(priceFrom);
request[0].setAveragePrice(priceFrom);
request[0].setPrice(priceFrom);
request[0].setQuantity(quantity);
request[0].setGrossAmtPcy(priceFrom);
request[0].setExchRate(quantity);
request[0].setGrossAmtTcy(priceFrom);
request[0].setNetAmountPcy(priceFrom);
request[0].setNetAmountTcy(priceFrom);
request[0].setAccrIntPcy(priceFrom);
request[0].setAccrIntTcy(priceFrom);
request[0].setAcquCostPcy(priceFrom);
request[0].setYieldType(YieldType.N);
request[0].setPurchaseYield(quantity);
request[0].setMarketYield(quantity);
request[0].setYtm(quantity);
request[0].setMduration(quantity);
request[0].setCurrPerNav(quantity);
request[0].setDesiredPerNav(quantity);
request[0].setCurrHolding(quantity);
request[0].setNoofDays(quantity);
request[0].setRealGlTcy(quantity);
request[0].setRealGlPcy(quantity);
request[0].setNowLater("N");
request[0].setIsAllocable(false);
request[0].setAcquCostReval(quantity);
request[0].setAcquCostHisTcy(quantity);
request[0].setAcquCostHisPcy(quantity);
request[0].setExIntPcy(quantity);
request[0].setExIntTcy(quantity);;
request[0].setAccrIntReval(quantity);
request[0].setAccrIntTcy(quantity);
request[0].setAccrIntPcy(quantity);;
request[0].setGrossAodTcy(quantity);
request[0].setGrossAodPcy(quantity);
request[0].setGrossAodReval(quantity);
request[0].setBankAccAmtAcy(quantity);
request[0].setBankAccAmtPcy(quantity);
request[0].setTaxAmountTcy(quantity);
request[0].setUnrelAmortPcy(quantity);
request[0].setUnrelAmortTcy(quantity);
request[0].setUnrelGlPcy(quantity);
request[0].setUnrelGlTcy(quantity);
request[0].setRealGlHisTcy(quantity);
request[0].setRealGlHisPcy(quantity);
request[0].setTradeFeesTcy(quantity);
request[0].setTradeFeesPcy(quantity);
boolean validateOnly = true;
HttpPost post = new HttpPost("http://localhost:8080/j_spring_security_check");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j_username", username));
nameValuePairs.add(new BasicNameValuePair("j_password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
post.abort();
}
HttpPost postURI = new HttpPost(uri);
// Setup the request parameters
BasicHttpParams params = new BasicHttpParams();
params.setParameter("CreateRequisitionRO", jsonROConverter.serialiseRequisionRO(request));
params.setBooleanParameter("validateOnly", validateOnly);
postURI.setParams(params);
postURI.setHeader("Content-type", "application/json");
HttpResponse responseURL = client.execute(postURI);
} catch (IOException e) {
e.printStackTrace();
}
}
These are the methods which i use to convert the Java POJO to Json;
public JSONArray serialiseRequisionRO(CreateRequisitionRO[] requisitionRO) {
JSONSerializer serializer = new JSONSerializer();
List<String> requisitionROList = new ArrayList<String>();
for(int i = 0 ; i< requisitionRO.length ; i++)
{
requisitionROList.add(serializer.serialize(requisitionRO[i]));
}
System.out.println("JSON : "+serializer.serialize(requisitionRO[0]));
return convertListToJSON(requisitionROList);
}
#SuppressWarnings("unchecked")
public JSONArray convertListToJSON(List<String> requisitionROList){
JSONArray requestCollection = new JSONArray();
JsonFactory jsonFactory = new JsonFactory();
for(int i = 0 ; i< requisitionROList.size() ; i++)
{
requestCollection.add(requisitionROList.get(i));
}
return requestCollection;
}
after doing all these i get the following exception -- java.io.EOFException: No content to map to Object due to end of input
I am in the guessing of that I do not set the parameter correctly I suppose but I am not sure about this.
Please help me to resolve this as I am struggling with this for more than three days.
I got the above java.io.EOFException: No content to map to Object due to end of input it is because the calling expects some argument where as i have sent the request without arguments.and this can also occur i the argument takes json array as parameter but i was sending json string which also was casting me the same exception.
Related
I tried a sample for post requests in IBM MF8 Java adapter.
Inside this adapter, I am trying to to call another Java adapter, SampleAdapter and want to do a POST with userDetails as parameter
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/balanced")
#OAuthSecurity(enabled = false)
public JSONObject generate(UserDetails userDetails , HttpRequest request, HttpSession session) throws UnsupportedEncodingException {
String messages = null;
String getProcedureURL = "/SampleAdapter/resource";
StringEntity requestEntity = new StringEntity(userDetails.toString(),ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(getProcedureURL);
httpPost.setEntity(requestEntity);
JSONObject jsonObj = null;
HttpResponse response;
try {
response = adaptersAPI.executeAdapterRequest(httpPost);
jsonObj = adaptersAPI.getResponseAsJSON(response);
messages = (String)jsonObj.get("subscriptionMessage");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("value", messages);
return json;
}
SampleAdapter has to get the object userDetails. So that I can use it in the back end for some operations.
But, here I am unable to get the data into SampleAdapter. Also, I tried returning some String from SampleAdapter.
I get the below error
{"responseText":"","error":"Response cannot be parsed to JSON"}
I know that IBM MF does the json conversion internally, but here how is it possible to do a POST from one adapter to adapter.
I see samples given only for GET requests.
Any suggestions to do for POST?
I wrote you a short example based on yours:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/balanced")
#OAuthSecurity(enabled = false)
public JSONObject generate() throws UnsupportedEncodingException {
String messages = null;
String getProcedureURL = "/SampleAdapter/resource/hello";
StringEntity requestEntity = new StringEntity("world", ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(getProcedureURL);
httpPost.setEntity(requestEntity);
JSONObject jsonObj = null;
HttpResponse response;
try {
response = adaptersAPI.executeAdapterRequest(httpPost);
jsonObj = adaptersAPI.getResponseAsJSON(response);
messages = "Hello " + (String)jsonObj.get("name");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = new JSONObject();
json.put("value", messages);
return json;
}
And here is the POST endpoint:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Path("/hello")
#OAuthSecurity(enabled = false)
public Map<String, String> hello(String name) {
Map<String, String> result = new HashMap<String, String>();
result.put("name", name);
return result;
}
I hope this will help you.
I wrote both Service and CLient part of application. I tested my service with "Postman" application and it is working fine with url = http://192.168.2.50:8084/FaceBusinessService/webresources/service/login?phone=123456789&password=1234
However when I try to call it on my Android Application it is not working. While debuging on service side I see that phone and password parameters are NULL.
Here is my service side :
#Path("login")
#POST
#Produces("application/json")
public String postJson(#QueryParam("phone")String phone, #QueryParam("password") String password) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(phone, password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}
Here is my android app side :
private UserInfo loginUser(String phone, String password) {
UserInfo userInfo = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.2.27:8084/FaceBusinessService/webresources/service/login");
try {
/*
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("phone", new StringBody(phone));
entity.addPart("password", new StringBody(password));
post.setEntity(entity);
*/
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Log.d(TAG, "POST String: " + post.toString());
try {
HttpResponse response = httpClient.execute(post);
if (response.getEntity().getContentLength() > 0) {
String json_string = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(json_string);
// TODO
return userInfo;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return null;
}
I tried both MultipartEntity and NameValuePair but none of them worked. Could you give me idea how to handle this issue?
Note that when testing with Postman you passed parameters (user name and password) as part of the URL (URL encoded), which can be directly retrieved on the server side. (you don't even need a POST request for this). Your objects are passed as string objects, not JSON objects.
In your client code , the URL is different because you're encoding the parameters as part of the POST request entity (payload). The parameters are packaged inside of the request/message body and not in the URL.
Now since your URL doesn't have the parameters, you should retrieve them by deserializing the request (desderialize the JSON request into a UserInfo object).
Note that you should rewrite your server side code completely as it should accept a application/JSON object but it apparently should return/produce a String object (plain/text or application/HTML).
I'm not familiar with GSON but your code might look something like
#Path("login")
#POST
#Produces("text/plain")
#Consumes("application/json")
public String postJson(UserInfo ui) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(ui.phone, ui.password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}
I know this should have been easy to find online but none of the articles addressed my issue so I am coming to SO for some help.I am trying to make an httppost request in android to a wcf restful web service. I want to create an xml and then I want to post that to the service and get a response from the service.
I have created a WCF Rest service and it has a method to accept the xml and respond back.Here is the code for the method:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "DoWork1/{xml}",
BodyStyle = WebMessageBodyStyle.Wrapped)]
XElement DoWork1(string xml);
public XElement DoWork1(string xml)
{
StreamReader reader = null;
XDocument xDocRequest = null;
string strXmlRequest = string.Empty;
reader = new StreamReader(xml);
strXmlRequest = reader.ReadToEnd();
xDocRequest = XDocument.Parse(strXmlRequest);
string response = "<Result>OK</Result>";
return XElement.Parse(response);
}
Here is android code to post xml :
String myXML = "<? xml version=1.0> <Request> <Elemtnt> <data id=\"1\">E1203</data> <data id=\"2\">E1204</data> </Element> </Request>";
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://192.168.0.15/Httppost/Service1.svc/DoWork1/"+myXML);
This code crasehes throwing an illegal character in the path exception.
How can I make post an xml file to this service from android. Any suggestions would be really appreciated.
public class HTTPPostActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
makePostRequest();
}
private void makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
}
To connect to WCF service on android you have to use external library like ksoap.
enter link description here
Then you can adapt for your needs this class:
public abstract class SoapWorker extends AsyncTask<SoapWorker.SoapRequest,Void,Object> {
public static class SoapRequest{
private LinkedHashMap<String,Object> params;
private String methodName;
private String namespace;
private String actionName;
private String url;
public SoapRequest(String url, String methodName,String namespace){
this.methodName = methodName;
this.params = new LinkedHashMap<>();
this.namespace=namespace;
this.actionName=this.namespace + "IService/" + methodName;
this.url=url;
}
public void addParam(String key,Object value){
this.params.put(key,value);
}
}
#Override
protected Object doInBackground(SoapRequest input) {
try {
SoapObject request = new SoapObject(input.namespace, input.methodName);
for(Map.Entry<String, Object> entry : input.params.entrySet()){
request.addProperty(entry.getKey(),entry.getValue());
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(input.url);
androidHttpTransport.call(input.actionName, envelope);
input.params.clear();
return parseResponse(envelope.getResponse());
} catch (Exception e) {
Log.e("SoapWorker", "error " + e);
return e;
}
}
#WorkerThread
public abstract Object parseResponse(Object response);
}
Use this class like:
SoapWorker.SoapRequest request = new SoapWorker.SoapRequest(URL,METHOD_NAME,NAMESPACE);
request.addParam(KEY,VALUE);
....
request.addParam(KEY,VALUE);
SoapWorker worker = new SoapWorker(){
#Override
public Object parseResponse(Object response) {
if(response==null)
return null;
//parse response
// this is background thread
return response;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// this is ui thread
//update your ui
}
};
worker.execute(request);
Use this asynck task only in application context.Pass data to Activity / fragment only using EventBus from green roboot or otto.
To post json from android to php, i used Volley library StringRequest object.
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// some code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//some code
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
String jsonCommands = new Gson().toJson(commands);
params.put("commands", jsonCommands);
return params;
}
};
And to catch the data in php and verify if it was sent correcttly, I used this
echo $_POST["commands"];
Output:
[{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"CF77 COIN FINDER\",\"url_image\":\"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg\",\"name\":\"CF77 COIN FINDER\",\"pid\":12,\"price\":500.0},\"product_quantity\":3},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"JEOSONAR 3D DUAL SYSTEM\",\"url_image\":\"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg\",\"name\":\"JEOSONAR 3D DUAL SYSTEM\",\"pid\":15,\"price\":500.0},\"product_quantity\":1},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"MAKRO POINTER\",\"url_image\":\"IMG_Macro.jpg\",\"name\":\"MAKRO POINTER\",\"pid\":18,\"price\":500.0},\"product_quantity\":3}]
I have noticed that when sending the json string with POST Method using Volley library, a lot of anti-slashes have been added to escape double quotes.
So here comes my problem:
I want to decode json to an array of objects in php, so i used
$commands = json_decode( $_POST["commands"],true);
But it always returns an empty array because of the invalide above json (caused by the anti-slashes).
Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? Or should i reformat the json in php and delete all the anti-slashes?
The problem is that you try to send the json data in the URL parameters.
You need to override the getBody() method to return the json data as request body, not as url parameters.
Eg:
/**
* Returns the raw POST or PUT body to be sent.
*
* #throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
return new Gson().toJson(commands).getBytes();
}
And then in PHP you can:
$jsonRequest = json_decode(stream_get_contents(STDIN));
first there is problem with the json itself is not build correctly is better to JSONObject for this, for example:
JSONObject js = new JSONObject();
try {
js.put("value",10);
} catch (JSONException e) {
e.printStackTrace();
}
String jss = js.toString();
you can check if the parse is success by copy the string and copy it in online parser like this http://json.parser.online.fr/
Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it.
function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
// search and remove comments like /* */ and //
$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
// search and remove all backslashes
$json = str_replace("\\","", $json);
if(version_compare(phpversion(), '5.4.0', '>=')) {
$json = json_decode($json, $assoc, $depth, $options);
}
elseif(version_compare(phpversion(), '5.3.0', '>=')) {
$json = json_decode($json, $assoc, $depth);
}
else {
$json = json_decode($json, $assoc);
}
return $json;
}
You can use this method to send json to web service.
public String makeServiceCallSubmit(String url, int method,
JSONArray object) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(object.toString());
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpResponse = httpClient.execute(httpPost);
}
httpEntity = httpResponse.getEntity();
Response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Response;
}
I am trying to pass an array of objects with several attributes to a php webservice using apache httpclient but I'm not sure how. I have tried to use JSON to encode the array and objects. The below methods create the JSON objects and then add them to a JSONArray:
createArray(){
JSONArray arr = new JSONArray();
}
public void addObj(long var1, int var2, int var3, int var4){
JSONObject obj;
try {
obj = new JSONObject();
obj.put("one:", var1);
obj.put("two:", var2);
obj.put("three:", var3);
obj.put("four:", var4);
arr.put(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
Next I have a class to pass my data to my webservice:
public class Upload {
private String userID = null;
private String password = null;
private String email = null;
Upload(String userID, String password, String email){
this.userID = userID;
this.password = password;
this.email = email;
}
public void uploadData(JSONArray arr) throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.mysite.com")
.setPath("/mypage.php")
.build();
HttpPost httppost = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Email", email));
String encoding = new String(
org.apache.commons.codec.binary.Base64.encodeBase64
(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userID + ":" + password))
);
httppost.setHeader("Authorization", "Basic " + encoding);
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
System.out.println(response);
HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
str = EntityUtils.toString(httpEntity);
System.out.println(str);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
I thought I might be able to simply pass the JSONArray as a parameter same as before by doing:
params.add(new BasicNameValuePair("JsonArray", arr));
But this doesn't work since add only seems to accept strings. How can I do it?
JsonObject has a toString method that gives you a string representation of the json object. I don't think you need a JsonArray, but in case you need just put it inside a JSONObject.
The point is HTTP only understands strings.
Another point is, in case your json is large, it is better to upload it rather than passing as a parameter.