process in-app apple receipt with java - java

I am using a java backend. After a user performs an in-app purchase, the front-end sends me the receipt. In turn, I am to send the receipt to apple for confirmation; then apple is to decode the receipt and send me back a JSON dictionary. My question is about sending the receipt back to apple so that I may get the json response. I am using the code below. But I keep getting {"status":21002} from apple and something about "Invalid cookie header". Any ideas how to solve this?
String url = "https://buy.itunes.apple.com/verifyReceipt";
DefaultHttpClient client = null;
try {
String input = IOUtils.toString(is);
log.info("THE INPUTSTREAM: " + input);
JSONObject receipt = new JSONObject();
receipt.put("receipt-data", input);
client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(receipt.toString());
entity.setContentType("application/json");
post.setEntity(entity);
HttpClientParams.setRedirecting(post.getParams(), false);
HttpResponse response = client.execute(post);
if (300 <= response.getStatusLine().getStatusCode()) {
throw new RuntimeException("No response from iTune store. status code: " + response.getStatusLine().getStatusCode());
}
if (null == response.getEntity()) {
log.info("Response is null");
throw new Exception("Response is null");
}
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
for (String line; null != (line = reader.readLine());) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
log.info("THE JSON" + json);
//Then work with json below
} catch (Exception e) {
throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build());
} finally {
if (null != client) {
client.getConnectionManager().shutdown();
}
}

No need cookie I think? try
HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.IGNORE_COOKIES);

Related

Can not find the Json object (Using org.json)

Microsoft Academic provided an API to get some general information from Microsoft academic. The response type is a Json Object. Using org.Json and following code, I have tried to read the response object but I have failed (need to download these jars + common-logging and common-codec) :
URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/academic/v1.0/evaluate?");
builder.setParameter("expr", "Composite(AA.AuN=='jaime teevan')");
builder.setParameter("count", "100");
builder.setParameter("attributes", "Ti,CC");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "Your-Key");
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject obj = new JSONObject(entity);
JSONArray arr = obj.getJSONArray("entities");
for (int i = 0; i < arr.length(); i++){
String post_id = arr.getJSONObject(i).getString("Ti");
System.out.println(post_id);
}
System.out.println(EntityUtils.toString(entity));
}
Which returns the following exception:
Exception in thread "main" org.json.JSONException: JSONObject["entities"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at org.json.JSONObject.getJSONArray(JSONObject.java:618)
How to fix this?
EDIT
Although it is easy to see an example of the response from the link I provided at the beginning of my question (Microsoft Academic), but for ease of readers I show it in here:
{
"expr": "Composite(AA.AuN=='jaime teevan')",
"entities":
[
{
"logprob": -15.08,
"Ti": "personalizing search via automated analysis of interests and activities",
"CC": 372,
},
{
"logprob": -15.389,
"Ti": "the perfect search engine is not enough a study of orienteering behavior in directed search",
"CC": 237,
}
]
}
Seems like the problem to me is you are not converting your response to string , you need to convert your response to string before passing it to JSONObject
HttpEntity entity = response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
entity.writeTo(os);
} catch (IOException e1) {
}
String contentString = new String(os.toByteArray());
or other way is
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String contentString = sb.toString(); // you can pass sb.toString() directly to jsonobject as well
and now pass contentString to JSONObject
JSONObject obj = new JSONObject(contentString);
JSONArray arr = obj.getJSONArray("entities");
Update : your can also use this which is also suggested by #Ömer Fadıl Usta
but i would strongly recommend to use HttpURLConnection for security and performance
Try to pass string JsonData to JSONObject :
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}

How send a json to server

I have a json that will be send to server in "Post".
There are parameters in json for 3 images to upload on server using multipart. I have no additional parameter to send it Multipart.
When I try it "PostMan" app of chrome to test it.
Here are 2 cases-
case 1:- select "raw" option in body & set content type "application json" in POSTMAN
Then all data had send to server expect images.
Case 2: Select "form-data" option in PostMan.
I have only to send some part of Json like images, certificates, venue, address, contact, achievement, level, at_home, certified, but unable to failed "coach_free_batch","coach_session" & "sports" section of json.
Please provide solution to upload all fields on server
Either idea to send "sports","coach_free_session" in second case by Postman or any other idea
Json
{"coach_free_batch":[{"sport_id":"10","batch_timing":{"end_time":"1:51 PM","start_time":"12:51 PM"},{"end_time":"11:51 AM","start_time":"10:51 AM"},{"end_time":"1:51 PM","start_time":"11:51 AM"}]},
{"sport_id":"4","batch_timing":[{"end_time":"1:52 PM","start_time":"12:52 PM"},
{"end_time":"3:52 PM","start_time":"2:52 PM"},{"end_time":"3:54 PM","start_time":"2:52 PM"}]}],
"coach_session":[{"timing":"2 Hour","rate":"24"},{"timing":"1 Hour","rate":"40"},
{"timing":"3 Hour","rate":"70"}],
"achievement":" national level",
"level":"Competitive","user_token":"XJnQCAz1ssuUCjgHtFs6","at_home":"1",
"sports":[{"user_sports_label_id":"7","sport_id":"2"},{"user_sports_label_id":"10","sport_id":"3"},
{"user_sports_label_id":"3","sport_id":"4"}],
"images":[{"image":"xxx"},
{"image":"xxx"}],
"experience":" more than 2 year","venue":"address","contact":"8236968542",
"certificates":[{"certificate":"certificate1"},{"certificate":"certifocate2"},{"certificate":"certificate3"}]}
Method for send Data as raw
public static String sendDataInJSONFormat(String url, String json) {
// initialize
InputStream is = null;
String result = null;
String url1 = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type",
"multipart/form-data; application/json; charset=UTF-8;text/plain");
HttpParams httpParameters = new BasicHttpParams();
int timeoutSocket = 25000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
e.printStackTrace();
}
return result;
}

java.lang.IllegalArgumentException: Illegal character in query at index 59

What i am doing:
I am trying to make a reverse geocoding in android
I am getting error as::
java.lang.IllegalArgumentException: Illegal character in query at index 59: http://maps.google.com/maps/api/geocode/json?address=Agram, Bengaluru, Karnataka, India&sensor=false
NOte: that request gets a json response in browser but not from my class below
This line is giving this error::
HttpGet httpget = new HttpGet(url);
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Use URLEncoder.encode() to encode the value of your address parameter "Agram, Bengaluru, Karnataka, India" before putting it in the URL string so that it becomes something like
http://maps.google.com/maps/api/geocode/json?address=Agram,+Bengaluru,+Karnataka,+India&sensor=false
i.e. spaces changed to + and other special octets represented as %xx.
Browsers do smart URL encoding for strings entered in the address bar automatically so that's why it works there.
Build your url like,
final StringBuilder request = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
request.append("&language=").append(Locale.getDefault().getLanguage());
request.append("&address=").append(
URLEncoder.encode(locationName, "UTF-8"));
I am using httpclient 4.3.3
String messagestr = "Welcome to Moqui World";
String url="http://my.example.com/api/sendhttp.phpauthkey="+URLEncoder.encode("17djssnvndkfjb110d3","UTF-8")+"&mobiles=91"+URLEncoder.encode(contactNumber,"UTF-8")+"&message="+URLEncoder.encode(messagestr,"UTF8")+"&sender="+URLEncoder.encode("WMOQUI","UTF-8")+"&route=4";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
It's working fine for me. I hope this may help you.

Request to server API using Java and JSON

I have documentation of server API with several methods. The problem is that I have never used API to work with server. What I can do to do it more easy?
Part of API documentation:
Method "Login":
POST http://api.example.com/login-ajax
Parameters:
email
password
Response:
{
"success":true,
"currentUser":222,
"userData":{
"displayName":"User",
"displayAvatarId":"asjhdsasduh",
"email":"qwerty#gmail.com",
"isEmailConfirmed":"0",
"sex":"m"
}
}
The response is JSON object, but I don't know how to send request to get this response.
Help me please.
UPGRADE
I tried to use Jsoup:
Connection.Response res = Jsoup.connect("http://api.example.com/login-ajax")
.data("email", "mail#gmail.com", "password", "pass")
.method(Connection.Method.POST)
.header("Accept", "application/json")
.header("X-Requested-With", "XMLHttpRequest")
.header("X-App-Api", "1.0")
.header("X-App", "iOS")
.ignoreContentType(true)
.execute();
Document document = Jsoup.parse(res.parse().outerHtml());
System.out.println(document.text());
The response is:
{"success":false,"exception":"Exception_User","message":"\u041c\u044b \u043d\u0435 \u043d\u0430\u0448\u043b\u0438 \u0432 \u0431\u0430\u0437\u0435 \u0442\u0430\u043a\u043e\u0435 \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u0435 \u044d\u043b. \u043f\u043e\u0447\u0442\u044b \u0438 \u043f\u0430\u0440\u043e\u043b\u044f. \u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435 \u0435\u0449\u0435 \u0440\u0430\u0437."}
UPGRADE 2
I also tried to use this one:
System.out.println(getJSON("http://api.example.com/login-ajax"));
public static String getJSON(String url) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("email", "mail#gmail.com");
c.setRequestProperty("password", "pass");
c.setRequestProperty("Accept", "application/json");
c.setRequestProperty("X-Requested-With", "XMLHttpRequest");
c.setRequestProperty("X-App-Api", "1.0");
c.setRequestProperty("X-App", "iOS");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(1000);
c.setReadTimeout(1000);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
System.out.println("200");
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
case 201:
System.out.println("201");
br = new BufferedReader(new InputStreamReader(c.getInputStream()));
sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
System.out.println("MalformedURLException");
} catch (IOException ex) {
System.out.println("IOException");
}
return null;
}
And the response is:
{"success":false,"exception":"Exception_Validation","message":"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 e-mail","errors":{"email":["\u041f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 e-mail."],"password":["\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043f\u0430\u0440\u043e\u043b\u044c"]}}
As I haven't used Jsoup so far I can't give detailed information on how to use it, but I had to work with Restlet and therefore created my own JSON messages (either via org.json.JSONObject or via plain String). A post-example using Restlet would look something like this:
try
{
// create a Restlet client
ClientResource cr = new ClienResource("http://api.example.com/login-ajax");
// create the JSON message
JSONObject message = new JSONObject();
message.put("email", "mail#gmail.com");
message.put("password", "pass");
// use HTTP POST method to send the JSON message
cr.post(message, MediaType.APPLICATION_JSON);
// receive the answer - error checks omitted!
Response response = cr.getResponse();
JsonRepresentation jsonRep = new JsonRepresentation(response.getEntity());
// process the JSON response
JSONObject json = jsonRep.getJsonObject();
System.out.println("success: "+json.get("success"));
System.out.println("current user: "+json.get("currentUser"));
// extract the user data
JSONObject userData = (JSONObject)json.get("userData");
System.out.println("display name: "+userData.get("displayName"));
System.out.println("display avatar Id: "+userData.get("displayAvatarId"));
System.out.println("email: "+userData.get("email"));
System.out.println("is email confirmed: "+userData.get("isEmailConfirmed"));
System.out.println("sex: "+userData.get("sex"));
}
catch (ResourceException | JSONException ex)
{
ex.printStackTrace();
}
HTH
Consider to use an Apache HTTP Client to create a connection to your HTTP server.
Its a general-purpose library for working with HTTP requests. There are plenty resources that illustrate the usage of HTTP client, Here is an example
I admit, I've never used JSoup so I can't really comment on your example.
Hope this helps,
Mark

How to call PHP function from Android?

I want to call specific php function on server and also to send some parameters.
Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app.
So, now I want to be able to call specific function and send parameter to it, how can I do that??
Sorry I didn't mansion that I need to call that function from Android.
here some code:
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/posloviPodaci/index.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parsing data
JSONArray jArray;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
items = new String[jArray.length()];
for(int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
items[i] = json_data.getString("naziv");
}
} catch (Exception e) {
// TODO: handle exception
}
Thanks in advance,
Wolf.
If you are working with an MVC framework, such as CakePHP, you can simply create a route to a function that will output whatever JSON you'd like.
Otherwise,
You can utilize something simple at the top of your index.php such as this:
<?php
function foo($bar) { echo $bar; }
if(isset($_GET['action']) && (strlen($_GET['action']) > 0)) {
switch($_GET['action']) :
case 'whatever':
echo json_encode(array('some data'));
break;
case 'rah':
foo(htmlentities($_GET['bar']));
break;
endswitch;
exit; # stop execution.
}
?>
This will let you call the url with a parameter of action.
http://10.0.2.2/posloviPodaci/index.php?action=whatever
http://10.0.2.2/posloviPodaci/index.php?action=rah&bar=test
If you need to pass more sensitive data, I recommend you stick with $_POST and utilize some form of encryption.
You can handle that on php side. Create a Json object with a field called command and maybe a list of arguments.
On the php end after you decode the json just do:
if($obj.command == "foo"){
foo($obj.arg[0],$obj.arg[1]);
}

Categories

Resources