How to pass array of variables to REST URL in android? - java

I have to make registration using REST URL. REST services are written in Java now i have to pass the set of parameters in that secGameIds parameter is like this [100,102]. Example registration using Insomnia:::
{
"firstName":"parent111",
"lastName":"sadfsdf",
"email":"abc#bbc.com",
"date":"2000-06-09",
"phoneNum":"8765654454",
"gender":"male",
**"secGameIds":[0,0],**
"roleId":102
}
How should i provide secGameIds parameter value is it a ArrayList or Array?
for remaining values i have created JSONObject class object and adding values to that object and 'm appending that object to url
{
JSONObject json = new JSONObject();
json.put("fistName","aaa");
..
..
HttpPost post = new HttpPost(uri);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
httpresponse = client.execute(post);
}
where as for secGameId i have tried like below,
{
int[] secGameId = {100,102};
}
-- gives me an error in back-end like "nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int[] out of VALUE_NUMBER_INT token"
I even tried by using
{
ArrayList<Integer> secGameId = new ArrayList<String>();
secGameId.add(100);
secGameId.add(102);
}
and passing to value...
{
json.put("secGameIds":secGameId)
}
again at server side i kicked with the same error.
Can anyone help me?

public static String httpPost(HashMap<String, String> map, String url,String token) {
Log.e("call ", "running");
HttpRequest request;
if(token!=null){
request = HttpRequest.post(url).accept("application/json")
.header("Authorization", "Token " + AppInfo.token).form(map);
}
else
request = HttpRequest.post(url).accept("application/json").form(map);
int responseCode = request.code();
String text = request.body();
Log.e("response", " "+responseCode+ " "+ text);
if(responseCode==400){
return "invalid_tocken";
}
else if(responseCode<200 || responseCode>=300) {
return "error";
}
return text;
}
Hope you can convert the JSONArray to HashMap. If you instead need to post it as a JSONArray itself, then OkHttp library will help you.

Related

Avoid escape foward slash in Android request with JSONObject

I'm trying to do a network request with HttpURLConnection and JSONObject, like this.
Step 1: class to serialize the request object
fun <T> GsonBuilder.getEncryptedJSON(request: T): JSONObject {
var encryptedJSON = JSONObject()
try {
var data = this
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapter(String::class.java, StringEncryptSerializer())
.registerTypeAdapter(java.lang.Long::class.java, LongEncryptSerializer())
.disableHtmlEscaping()
.create()
.toJson(request)
encryptedJSON = JSONObject(data)
} catch (exception: JSONException) {
Log.e("exception-json", exception.toString())
}
return encryptedJSON
}
Step 2: Class UploadRequest that extends HttpRequest and has a property called body witch is type of JSONObject
uploadRequest.body = GsonBuilder().getEncryptedJSON<UploadRequest>(this)
Step 3: request after a few steps, is the request HTTP class
postData = request.getBody().toString().getBytes(StandardCharsets.UTF_8);
wr = new DataOutputStream(connection.getOutputStream());
wr.write(postData);
wr.flush();
I've seen: After transform my body into JSONObject, the problem happens.
The result I expected is bellow:
{"fileName":""0NKTqOdZ154T/ksxOwdx0VzHNQmGfM0UlpPrreb0vFnGh/Rw3UZEx94aUAuZtr8lW/da07/h/RNoyXpMqpGXKA===="}
But, everytime I've seen the log inside the gateway, the request content is ESCAPING FOWARD SLASHES, like this
{"fileName":""0NKTqOdZ154T\/ksxOwdx0VzHNQmGfM0UlpPrreb0vFnGh\/Rw3UZEx94aUAuZtr8lW\/da07\/h\/RNoyXpMqpGXKA===="}
Do you have any idea why this happen?!
Thank you!

Converting from DescribeSObjectResult to JsonArray (or to HttpEntity)

A couple of weeks ago, I asked a question about reading Salesforce data using the SOAP API instead of the REST API (see Trying to use Apache Gobblin to read Salesforce data using SOAP API(s) instead of REST API ), but unfortunately nobody answered it, and so I am trying to implement the solution (with a little help) directly.
Using the REST API, the existing code that reads in a table's definition (by making a call to the REST API) looks like this:
// the URL starts with the Salesforce REST API endpoint, and ends with "/describe"
public String getSchema(String url, String accessToken, HttpClient httpClient) {
String jsonStr;
HttpRequestBase httpRequest = new HttpGet(url);
if (accessToken != null) {
httpRequest.addHeader("Authorization", "OAuth " + this.accessToken);
}
httpRequest.addHeader("Content-Type", "application/json");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpRequest);
StatusLine status = httpResponse.getStatusLine();
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
jsonStr = EntityUtils.toString(httpEntity);
}
if (status.getStatusCode() >= 400) {
System.out.println("There was an error. Http Status code of " + status.getStatusCode());
EntityUtils.consumeEntity(httpEntity);
return null;
}
return jsonStr;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return jsonStr;
}
I would like to write a method that uses the Salesforce SOAP API (using the generated "partner.wsdl" file) similar to the following incomplete code:
public String getSchemaViaSoap(String tableName) {
String jsonStr;
PartnerConnection partnerConnection = ...;
try {
DescribeSObjectResult[] dsrArray = partnerConnection.describeSObjects(new String[] { entity });
// Since we described only one sObject, we should have only
// one element in the DescribeSObjectResult array.
DescribeSObjectResult dsr = dsrArray[0];
String jsonStr = ...; /* this is where I need help in converting dsr into a similar JSON string. */
} catch (ConnectionException e) {
e.printStackTrace();
log.error("Error getting connection", e);
System.out.println("Error getting connection" + e);
return null;
}
return jsonStr;
}
Any sort of help in determining how to convert from the DescribeSObjectResult object to a similar JsonString / HttpEntity / StringEntity object would be greatly appreciated.
You have consumed the WSDL, right? The DescribeSObjectResult is a normal class in your project. So... my Java is rusty but seems the question is simple "how to convert a Java object to JSON"?
There are libraries for this, right? Jackson for example. This helps? Converting Java objects to JSON with Jackson
I'm not sure if you'll end with identical result but should be close enough.

Java Jersey Web Service: consume JSON request

I have a web service made witj Java and Jersey. I want to receive a JSON request and parse the json for savethe values stores on the json on the database.
This is mi web service code:
#Path("companies")
public class Companies {
#Path("add")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public JSONObject addCompanies(JSONObject inputJsonObj){
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
The client side is made with AngularJS:
$scope.company = "";
$scope.submit = function(){
// Writing it to the server
//
var dataObj = {
company : $scope.company
};
var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
notify("succes");
});
res.error(function(data, status, headers, config) {
//alert( "failure message: " + JSON.stringify({data: data}));
notify("fail");
});
};
This is the error I'm getting when I pass the JSON to the web service:
Status Code:415
And this is the request I am sending:
{"company":"Testing2"}
This is my Network tab:
Without further configuration, JSONObject is not something that Jersey supports. You will just need to work with Strings
public String addCompanies(String json){
JSONObject inputJsonObj = new JSONObject(json)
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj.toString();
}
If you really want to use JSONObject you can check out this post.
See Also:
JAX-RS Entity Providers to learn how Jersey handle serialization an deserialization.

sending empty content with HttpClient

I am trying to connect to an API of another company.
from the doc there is ::
even with your GET request, you'll need to include the Java equivalent of
curl_setopt($ch, CURLOPT_POSTFIELDS, $content), and you can set $data equal
to an empty array.
$content in their example is an empty JSON array.
I am using org.apache.commons.httpclient.
i am not sure how to add post fields to a org.apache.commons.httpclient.methods.GetMethod or if it is even possible.
i tried faking with a Content-Length of 2 but the GET times out (probably looking for content that i am not providing. if i remove the content-length i get an invalid response from the api server)
HttpClient client = new HttpClient();
GetMethod method = new GetMethod("https://api.xxx.com/account/");
method.addRequestHeader("Content-Type", "application/json");
method.addRequestHeader("X-Public-Key", APKey);
method.addRequestHeader("X-Signed-Request-Hash", "xxx");
method.addRequestHeader("Content-Length", "2");
int statusCode = client.executeMethod(method);
I don't think GetMethod includes any means of attaching a request body, because a GET request isn't supposed to have a body. (But having a body isn't actually prohibited, either - see: HTTP GET with request body .)
You're trying to use documentation written with a different language and a different client library in mind, so you'll have to use trial and error a bit. It sounds like they expect a request with no body, and you already have that. There's no good reason why they'd require a "Content-Length" with GET, but if that's the case, try setting it to 0.
This is how i resolved this issue
Created this class
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(URI uri) {
super();
setURI(uri);
}
public HttpGetWithEntity(String uri) {
super();
setURI(URI.create(uri));
}
#Override
public String getMethod() {
return HttpGet.METHOD_NAME;
}
}
Then the calling function looks like
public JSONObject get(JSONObject payload, String URL) throws Exception {
JSONArray jsonArray = new JSONArray();
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGetWithEntity myGet = new HttpGetWithEntity(WeeblyAPIHost+URL);
myGet.setEntity( new StringEntity("[]") );
myGet.setHeader("Content-Type", "application/json");
myGet.setHeader("X-Public-Key", APIKey);
HttpResponse response = client.execute(myGet);
JSONParser parser = new JSONParser();
Object obj = parser.parse( EntityUtils.toString(response.getEntity(), "UTF-8") ) ;
JSONObject jsonResponse = (JSONObject) obj;
return jsonResponse;
}

How to update a playlist using SoundCloud api wrapper for java

The soundcloud documentation has no sample for updating a playlist using java wrapper. I tried something like this but it didn't update the tracks. And no error messages returned.
HttpResponse resp = wrapper
.put(Request.to("/me/playlists/123")
.with("playlist[title]", "updated title", "playlist[tracks]", "[
{id: 10001},
{id: 10002}
]"));
Any ideas?
The problem is that you're using a mix of Rails style form parameters and JSON.
There are two options:
1) Only use form parameters:
HttpResponse resp = api.put(Request.to("/playlists/123")
.with("playlist[title]", "updated title")
.with("playlist[tracks][][id]", 10001)
.with("playlist[tracks][][id]", 10002));
2) Submit playlist data as JSON:
private void updatePlaylist() {
JSONObject json = createJSONPlaylist("updated title", 10001, 10002);
HttpResponse resp = api.put(Request.to("/playlists/123")
.withContent(json.toString(), "application/json"));
}
private JSONObject createJSONPlaylist(String title, long... trackIds) throws JSONException {
JSONObject playlist = new JSONObject();
playlist.put("title", title);
JSONObject json = new JSONObject();
json.put("playlist", playlist);
JSONArray tracks = new JSONArray();
playlist.put("tracks", tracks);
for (long id : trackIds) {
JSONObject track = new JSONObject();
track.put("id", id);
tracks.put(track);
}
return json;
}
Check out the tests in the wrapper to see them in action:
without JSON
with JSON

Categories

Resources