Scenario : Pass username and password in a json object to restful webservice and get a json object in return. Yeah, I know, Its simple but I can't get it work.
I have been trying to this from several days. So far, I have tried this:
My restful webservice code
#POST
#Path("/testJson")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject testJson(JSONObject inputJsonObj) throws Exception {
JSONObject myjson = new JSONObject();
if(inputJsonObj != null){
System.out.println("=================================");
System.out.println("JSON object = " + inputJsonObj.toString());
System.out.println("=================================");
}
else{
System.out.println("JSON is NULL");
}
myjson.put("success", "1");
System.out.println(myjson.toString());
// return "string returned";
return myjson;
}
And inside my android acivity, the code is
// POST request to <service>/SaveVehicle
HttpPost request = new HttpPost(myURL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setHeader("user-agent", "Yoda");
try {
// Build JSON string
// JSONStringer vehicle = new JSONStringer().object()
// .key("getItInputTO").object().key("zipCode").value("90505")
// .key("financingOption").value("B").key("make")
// .value("Scion").key("baseAmountFinanced").value("12000")
// .key("modelYear").value("2010").key("trimCode")
// .value("6221").key("totalMSRP").value("15000")
// .key("aprRate").value("").endObject().endObject();
JSONObject myjson = new JSONObject();
myjson.put("1", "first");
myjson.put("2", "second");
StringEntity entity = new StringEntity(myjson.toString());
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// HttpResponse response = httpClient.execute(request, localContext);
HttpResponse response = httpClient.execute(request);
resCode = response.getStatusLine().getStatusCode();
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode() + "",
Toast.LENGTH_LONG).show();
if (resCode == 200) {
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode() + "",
Toast.LENGTH_LONG).show();
HttpEntity entity2 = (HttpEntity) response.getEntity().getContent();
String text = getASCIIContentFromEntity(entity);
if(text!=null){
JSONObject obj = new JSONObject(text);
lblMsg.setText("Successful!");
}
// BufferedReader in = new BufferedReader(new
// InputStreamReader(response.getEntity().getContent()));
//
//
// String line = "";
// StringBuffer returnFromServer = new StringBuffer();
//
// while ((line = in.readLine()) != null) {
// returnFromServer.append(line);
// }
// // Toast what we got from server
// Toast.makeText(getApplicationContext(),
// returnFromServer.toString(), Toast.LENGTH_LONG).show();
//
// if (entity != null) {
// entity.consumeContent();
// }
}
} catch (Exception e) {
// TODO: handle exception
}
The commented sections show previous tries.
Output that I get on server console
=================================
JSON object = {}
=================================
{"success":"1"}
My server side receiver json object is not getting populated i don't know why.
Note:
I have INTERNET and many other permissions in my android manifest.
My webservice is up and running.
I have all the required jars i.e. jersey, json etc
I am using Tomcat 7 for restful webservice
I would highly appreciate any help.
Thanks
I have the same problem as yours.
I don't know why, but the temporary solution i am using is creating a class to handle those parameters.
That means using Jackson to convert Json Object <=> "Your Class"
See this tutorial for more information:
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
===================================
And I just found this topic, it may be more useful than the upper solution:
Jersey POST Method is receiving null values as parameters
Related
Can someone guide me how to test iOS(auto-renewable IAP) Receipt Validation API by using Sandbox URL?
I have tried this below snippet.
public void validateReceiptData(VerifyReceiptRequestView requestview) {
System.out.println("validateReceiptData ....................");
String VERIFICATION_URL=" https://sandbox.itunes.apple.com/verifyReceipt";
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(VERIFICATION_URL);
JSONObject requestData = new JSONObject();
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
StringEntity requestEntity = new StringEntity(requestData.toString());
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(requestEntity);
HttpResponse response =httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseBody);
System.out.println("responseJSON -------------->"+responseJSON);
}catch(Exception e) {
e.printStackTrace();
}
}
But I need sample request data for the below mentioned fields
requestData.put("receipt-data", requestview.getReceiptdata());
requestData.put("password", requestview.getPassword());
Does the field requestview.getReceiptdata() requires any Valid Purchased receipt or does Apple provides any sample receipt data to test this API in SandBox environment.
I am trying to make a HTTP PATCH request in Java, but despite my efforts this is not working.
I am trying to PATCH a Json, here is my code:
HttpResponse response = null;
BufferedReader rd = null;
StringBuffer result = new StringBuffer();
String line = "";
HttpClient httpclient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch("http://myURL");
JsonArrayBuilder Abuilder = Json.createArrayBuilder();
JsonObjectBuilder oBuilder = Json.createObjectBuilder();
for(int i=0;i<48;i++){
Abuilder.add(i+1);
}
oBuilder.add("date", "2016-09-08");
oBuilder.add("values",Abuilder);
JsonObject jo = Json.createObjectBuilder().add("puissance", Json.createObjectBuilder().add("curves",Json.createArrayBuilder().add(oBuilder))).build();
try{
//Execute and get the response.
StringEntity params =new StringEntity(jo.toString());
params.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPatch.setEntity(params);
response = httpclient.execute(httpPatch);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
System.out.println(line);
result.append(line);
}
}catch(Exception e){
}
When I execute this request, I get a
"400 Error: The request has an invalid header name".
When I execute this request using Postman, this is working fine.
I am quite new at HTTP requests so do not hesitate to ask if you need more details.
StringEntity.setContentEncoding is used to set the Encoding type,
You should use StringEntity.setContentType to set the ContentType
Problem-
RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject("http://localhost:8080/employee/1", requestBody, String.class);
Solution-
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject("http://localhost:8080/employee/1?_method=patch", requestBody, String.class);
i m trying to build android app that can get the location of user from Google Geolocation Api. I configuration and setup billing account
My Setting are
Increase quota to 100/request/user
Billing account Setup
Allowed ip : any
i m using Async Task class
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("https://www.googleapis.com/geolocation/v1/geolocate?key=API_KEY");
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("homeMobileCountryCode", 310);
jsonObject.accumulate("homeMobileNetworkCode", 410);
jsonObject.accumulate("radioType", "gsm");
jsonObject.accumulate("carrier", "vodafone");
JSONArray cellTowersArray = new JSONArray();;
JSONObject cellTowerObject = new JSONObject();;
cellTowerObject.accumulate("cellId", 42);
cellTowerObject.accumulate("locationAreaCode", 415);
cellTowerObject.accumulate("mobileCountryCode", 310);
cellTowerObject.accumulate("mobileNetworkCode", 410);
cellTowerObject.accumulate("age", 0);
cellTowerObject.accumulate("signalStrength", -60);
cellTowerObject.accumulate("timingAdvance", 15);
cellTowersArray.put(cellTowerObject);
jsonObject.accumulate("cellTowers", cellTowersArray);
JSONArray wifiAccessPointsArray = new JSONArray();
JSONObject wifiAccessPointObject = new JSONObject();
wifiAccessPointObject.accumulate("macAddress", "01:23:45:67:89:AB");
wifiAccessPointObject.accumulate("age", 0);
wifiAccessPointObject.accumulate("channel", 11);
wifiAccessPointObject.accumulate("signalToNoiseRatio", 40);
wifiAccessPointsArray.put(wifiAccessPointObject);
jsonObject.accumulate("wifiAccessPoints", wifiAccessPointsArray);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);;
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work";
}
catch (MalformedURLException e) {
Log.e("YOUR_APP_LOG_TAG1", "", e);
}
catch (IOException e) {
Log.e("YOUR_APP_LOG_TAG2", "", e);
}
catch (Exception e) {
Log.e("YOUR_APP_LOG_TAG3", "", e);;
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d("result", result);
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));;
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
but i m still getting 403 Error, allowed Ip is not Configuration
Help/ Suggestion are appreciated.thanks
I figure it our Myself. if you are having trouble using Google gelocation Api and getting 403 error. then you have to follow these steps . it is Simple :)
decrease the no of API request to 0
then disable the Geolocation API
Create a New Project
Then enable the Google Geolocation Api
Add / increase the No of request of API
Create the Android API Key
Server API key
Use it
and you are good to go , now you can use your google geolocation api with ease
Hope it will help
thanks
I am developing an android app which uses a login api, which will allow its web users to login with their same credentials on the android device.....
the url for the api is
https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user=ecoachguest&pass=ecoachguest
which retuns a response in json
JSON object: {
status: <success or error>,
msg: <response message>,
profile: <user profile object>
}
I tried this code which I found searching on the internet but it isn't working,
private void doLogin(View view) {
//ALERT MESSAGE
_spinner.setVisibility(View.VISIBLE);
Toast.makeText(mContext, "connecting to server.... ",
Toast.LENGTH_SHORT).show();
// URLEncode user defined data
String usernameValue = username.getText().toString();
String passValue = password.getText().toString();
// Create http cliient object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+usernameValue+"&pass="+passValue;
Log.i("httpget", URL);
try
{
String SetServerString ;
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
System.out.println(usernameValue);
System.out.println(passValue);
// Show response on activity
Toast.makeText(getBaseContext(),SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"Fail",Toast.LENGTH_LONG).show();
_spinner.setVisibility(View.INVISIBLE);
}
}
will appreciate the help or the positive direction thanks :)
Change your code to get the HttpResponse like below,
String responseBody = "";
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
Log.i("GET Response Code ",responseCode + "");
switch(responseCode) {
// Means server is responding
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
// Now you can try printing your returned string here, before you go for JSON parsing
}
break;
// Add more case statements to handle other scenarios
}
The code is simple, but if still unable to understand, don't hesitate to ask.
I have a java program that passes data to a php webservice via apache httpclient. Currently all it is passing is user authentication details and a string variable. These are received and handled fine on the PHP side. I would also like to pass an ArrayList of objects in a way that I can read the object attributes from PHP. Is there a way to do this directly in the same way I'm passing parameters or do I need to use JSON objects or something else? The objects contained have 4 attributes, not just name value pairs.
My Java code looks like so:
public void upload(ArrayList<MyObject> myList) throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.mysite.com")
.setPath("/webservice.php")
.build();
HttpPost httppost = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("var1", var1));
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();
}
}
EDIT:
My use case for this is basically that I want to update a MySQL database table on my server with each attribute of my java object being the value of one field (i.e. one object = one table row). So I want to be able to pass my ArrayList such that I can add multiple rows to my database table in one go.
EDIT2. Okay I now have the following method to construct my JSONArray where the variables passed were previously the attributes of my object. The JSON objects are now what would previously have been my object, and the jsonArray is what would previously have been my ArrayList. Is this correct? How can I post it from my httpclient?
public void constructJSON(long var1, int var2, int var3, int var4){
JSONObject obj;
JSONArray jsonArray = new JSONArray();
try {
obj = new JSONObject();
obj.put("var1:", var1);
obj.put("var2:", var2);
obj.put("var3:", var3);
obj.put("var4:", var4);
jsonArray.put(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}