Java app store receipt validation - java

I am trying to validate an Apple App Store receipt from a Java service. I can not get anything back other than an error 21002, "Receipt Data Property Was Malformed". I have read of others with the same problem, but, have not see a solution. I thought this would be fairly straight forward, but, have not been able to get around the error. Here is my code:
EDIT By making the change marked // EDIT below, I now get an exception in the return from the verifyReceipt call, also makred //EDIT:
String hexDataReceiptData = "<30821e3b 06092a86 4886f70d 010702a0 .... >";
// EDIT
hexDataReceiptData = hexDataReceiptData.replace(">", "").replace("<", "");
final String base64EncodedReceiptData = Base64.encode(hexDataReceiptData.getBytes());
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("receipt-data",base64EncodedReceiptData);
}
catch (JSONException e)
{
e.printStackTrace();
}
URL url = new URL("https://sandbox.itunes.apple.com/verifyReceipt");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
//Send request
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonObject.toString());
wr.flush();
//Get Response
BufferedReader rd =
new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder httpResponse = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
httpResponse.append(line);
httpResponse.append('\r');
}
wr.close();
rd.close();
// EDIT
// {"status":21002, "exception":"java.lang.IllegalArgumentException"}

As posted here: Java and AppStore receipt verification, do the base64 encoding in iOS and send to the server. But, why?

Related

Why HttpURLConnection.getInputStream stop working in Java

My program below stopped at the line:
InputStream is = conn.getInputStream();
Neither error message popped up nor any output displayed on the console.
I am running Eclipse Oxygen 4.7.0 on Red Hat Enterprise Linux Server release 7.4.
public static void solveInstance(String instanceName){
// solve a problem instance
try{
String query_url = "http://localhost:8807/scheduler";
// read Request to a JSON Object
JSONParser parser = new JSONParser();
JSONObject request = (JSONObject) parser.parse(new FileReader(instanceName));
// open connection
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// POST Request
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(request.toString());
osw.close();
// Get Response
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer response = new StringBuffer();
while(( inputLine = in.readLine()) != null )
{
response.append(inputLine);
}
in.close();
// Write response to a file
JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
String responseFile = /path_to_result/result.json;
FileWriter fileWriter = new FileWriter(responseFile);
fileWriter.write(jsonObj.toString());
fileWriter.flush();
fileWriter.close();
System.out.println("Solved" + instanceName);
}
catch(Exception e) {
System.out.println(e);
}
}
I noticed that the similar question is asked InputStream is = httpURLConnection.getInputStream(); stop working
but it was for Android and no solution was given there.
Does anyone have some idea on that? Do not hesitate to point out anything else wrong in my code.
Thanks a lot!
Your server isn't responding.
It would be wise to set a read timeout, with conn.setReadTimeout(5000) (say). Adjust the timeout as necessary.
Check response code
int response = connection.getResponseCode();
If you get 301 it means that your resource is redirected. Try to change URI from http to https.
It helped in my case.

How to get correct data from HTTP Request

I'm trying to get my user information from stackoverflow api using a simple HTTP request with GET method in Java.
This code I had used before to get another HTTP data using GET method without problems:
URL obj;
StringBuffer response = new StringBuffer();
String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in this case I'm getting just stranger symbols when I print the response var, like this:
�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���#�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����
thanks in advance.
The content is likely GZIP encoded/compressed. The following is a general snippet that I use in all of my Java-based client applications that utilize HTTP, which is intended to deal with this exact problem:
// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection
// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
// Format is GZIP
// Replace inputSteam with a GZIP wrapped stream
inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text
BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...
This relies on the following imports: java.util.zip.GZIPInputStream; java.util.zip.Inflater; and java.util.zip.InflaterInputStream.

Java client POST to php script - empty $_POST

I have researched extensively and cannot find a solution. I have been using the solutions provided to other users and it does not seem to work for me.
My java code:
public class Post {
public static void main(String[] args) {
String name = "Bobby";
String address = "123 Main St., Queens, NY";
String phone = "4445556666";
String data = "";
try {
// POST as urlencoded is basically key-value pairs
// create key=value&key=value.... pairs
data += "name=" + URLEncoder.encode(name, "UTF-8");
data += "&address=" +
URLEncoder.encode(address, "UTF-8");
data += "&phone=" +
URLEncoder.encode(phone, "UTF-8");
// convert string to byte array, as it should be sent
byte[] dataBytes = data.toString().getBytes("UTF-8");
// open a connection to the site
URL url = new URL("http://xx.xx.xx.xxx/yyy.php");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
// tell the server this is POST & the format of the data.
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(dataBytes.length);
conn.getOutputStream().write(dataBytes);
conn.getInputStream();
// Print out the echo statements from the php script
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null)
System.out.println(line);
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
and the php
<?php
echo $_POST["name"];
?>
The output I receive is an empty line. I tested to see if it was a php/server side issue by making an html form that sends data over to a similar script and prints the data on the screen and that worked. But, for the life of me, I cannot get this to work with a remote client.
I am using Ubuntu server and Apache.
Thank you in advance.
The problem is actually in what you read as output. You are doing two requests:
1)conn.getInputStream(); - sends POST request with desired body
2)BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream())); - sends empty GET request (!!)
Change it to:
// ...
conn.getOutputStream().write(dataBytes);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
and see result.

405 - method not allowed calling web service from struts

I have a data access object which calls a web service. In my browser I can hit the web service using a url and it is successful.
http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json
But when try to execute the code below in my data access object I get a 405 error saying method not allowed.
String requestURI = "http://mycompany:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("GET");
httpCon.setRequestProperty("Accept", "application/json");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
int responseCode = httpCon.getResponseCode();
String responseMessage = httpCon.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
String jsonResponse = sb.toString();
out.close();
httpCon.disconnect();
Can someone help me with what might be wrong here?
Also maybe there is a better way to execute a web service to an external application and read the response using struts? Or do people think this method is okay?
thanks
If u are using GET method. Try the below code.
string url = String.Format("http://somedomain.com/samplerequest?greeting={0}",param);
WebClient serviceRequest = new WebClient();
serviceRequest.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = serviceRequest.DownloadString(new Uri(url));
Thanks for your ideas however non of them were quite right. I fixed the 405 using the code below...
String requestURI = "http://myserver:9080/ReportingManager/service/repManHealth/importHistoryTrafficLightStatus.json";
URL url = new URL(requestURI);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
By calling httpCon.getOutputStream()); you're not sending a HTTP GET anymore, but a HTTP POST.
Note: This is under the assumption you end up getting the implementation provided by Sun. Which will change GET to POST for backwards compatibility.

Send data using POST to java server from Android client and get JSON response

I am completely new to Android programming. I have come across the following problem -
I want to validate the credentials of the user who uses the application. For this I want to use POST method to send the Login details to the server. From there I want to get response in JSON format. I don't know how to receive the response. I am using Java for server side programming.
P.S. I would deal with security concerns bit later.
Following is my Android code. I know it is a mess.. Please help.
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("address");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
return -1;
}
There's an open source class you can use for just this, and you can easily browse the code to see how it works. There are actually many open source libs that do this, but the following is among the cleanest and easiest to work with in my opinion.
https://github.com/kevinsawicki/http-request/blob/master/lib/src/main/java/com/github/kevinsawicki/http/HttpRequest.java
And your code will probably look something like this:
Map<String, String> params = new HashMap<String, String>();
params.put("username", mUsername);
params.put("password", mPassword);
String response = HttpRequest.post(url).form(params).body();
EDIT
My original answer including the params map in to post method would have sent the request as a POST but the params in the url. The corrected version (form method) sends the params in the body.
You can convert your json response to a JSONObject class.
Look this app, the code is very simple.
#Override
public List<User> getRanking() {
final List<User> result = new ArrayList<User>();
String url = "http://quiz-exmo.rhcloud.com/rest/user/ranking/";
String json = HttpUtil.doGet(url);
try {
final JSONObject resultJsonObject = new JSONObject(json);
final JSONArray jsonArray = resultJsonObject.getJSONArray("users");
for (int index = 0, total = jsonArray.length(); index < total; index++) {
final JSONObject jsonObject = jsonArray.getJSONObject(index);
final User user = new User();
user.name = jsonObject.getString("name");
user.email = jsonObject.getString("email");
user.score = jsonObject.getInt("points");
result.add(user);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return result;
}
https://github.com/exmo/equizmo-android/blob/master/maven/equizmo/src/main/java/br/gov/serpro/quiz/service/rest/UserServiceRest.java

Categories

Resources