I currently have a PHP page, that I need to port over so that it runs through Java instead of PHP. Part of that conversion requires running a Sha1 conversion onto a string generated by PHP's http-build-query I need to get the exact same string output in Java that PHP would generate.
So for example:
I have a complex JSON object. (syntax is not exact)
{"user":{"name:'Bob Smith',
"age":47,
"sex":'M',
'dob':'5/12/1956'},
'pastimes'['golf', 'opera', 'poker', 'rap'),
'children'['bobby':{'age':12,'sex':'M'},
'sally'{'age':8, 'sex':'F'}],
'CEO'}};
I need to convert it to a keyvalue string such as
user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO
Essentially, I need to do what the http-build-query in PHP does with complex arrays.
Related
In a Java method that receives a java.util.UUID Object, I would like to display this object as a string in the .NET/C# format (CSUUID).
Currently I am only able to display it in the Java format (JUUID) :
static String GetStringFromUuid (java.util.UUID myUuid){
return myUuid.toString();
}
Current output: "46c7220b-1f25-0118-f013-03bd2c22d6b8"
Desired output: "1f250118-220b-46c7-b8d6-222cbd0313f0"
Context:
The UUID is stored in MongoDB and is retrieved with the Java ETL program Talend (tMongoDBInput component).
In the Java program, the method already receives the UUID as a java.util.UUID Object (I do not have directly access to the BinData in the program).
I need to display the UUID in the C# format since other programs already display the UUIDs with the C# format.
In case it might be useful, the example data is stored in MongoDB like this:
BinData(3,"GAElHwsix0a41iIsvQMT8A==")
I need a solution in Java.
Guid is represented by 16 bytes. For various reasons, both Java and .NET do not just print those bytes in order when you call toString. For example, if we look at base-64 encoded guid from your question:
GAElHwsix0a41iIsvQMT8A==
In hex form it will look like this:
18-01-25-1f-0b-22-c7-46-b8-d6-22-2c-bd-03-13-f0
Java toString produces this (if we format as above):
46-c7-22-0b-1f-25-01-18-f0-13-03-bd-2c-22-d6-b8
.NET ToString produces this:
1f-25-01-18-22-0b-46-c7-b8-d6-22-2c-bd-03-13-f0
If you look at this for some time - you will notice that both java and .NET strings represent the same 16 bytes, but positions of those bytes in output string are different. So to convert from java representation to .NET you just need to reorder them. Sample code (I don't know java, so probably it could be done in a better way, but still should achieve the desired result):
static String GetStringFromUuid (java.util.UUID myUuid){
byte[] bytes = new byte[16];
// convert uuid to byte array
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.putLong(myUuid.getMostSignificantBits());
bb.putLong(myUuid.getLeastSignificantBits());
// reorder
return String.format("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
bytes[4],bytes[5],bytes[6],bytes[7],
bytes[2],bytes[3],bytes[0],bytes[1],
bytes[15],bytes[14],bytes[13],bytes[12],
bytes[11],bytes[10],bytes[9],bytes[8]);
}
We can just keep the GUID as string, if the c# function is receiving the string and it needs to be displayed or sent to some service as string
Just in case if you want to parse it.
You can use the link for GUID parsing logic example
For creating new GUID in C#, use
var guid = System.Guid.NewGuid();
var guidString = guid.ToString();
For creating new UUID in Java, use
UUID uuid = java.util.UUID.randomUUID();
String uuidString = uuid.toString();
I am working with the GCS API, attempting to create a survey with image data.
I am using the NuGet package Google.Apis.ConsumerSurveys.v2 version 1.14.0.564 on the .Net platform. I can create surveys that do not contain image data without problem. However, when I try to create a survey with image data I receive an error from the API.
I have on hand base64 encoded png format image data. My images display properly in an IMG tag on a web page when the src attribute is set to
'data:image/png;base64,<image base64 string>'
I want to send this image data to the API to populate the survey image. My understanding is that I need to set the Data property of the Google.Apis.ConsumerSurveys.v2.Data.SurveyQuestionImage object to a string containing the image data. I have not been successful.
I first decode my base64 string to a byte array:
byte[] bytes = Convert.FromBase64String(<image base64 string>);
I have tried setting the Data property in the SurveyQuestionImage object as:
image.Data = Encoding.Unicode.GetString(bytes);
This results in this error from the API:
Google.Apis.Requests.RequestError Invalid value for ByteString: <the Data string>
I have also tried converting the byte array to a hexadecimal encoded string as:
StringBuilder sb = new StringBuilder(bytes.Length);
foreach (Byte b in bytes)
{
sb.Append(b.ToString("X2"));
}
image.Data = sb.ToString();
This results in the more hopeful error:
Google.Apis.Requests.RequestError Invalid Value supplied to API: image_data was bad. Request Id: 579665c300ff05e6c316a09e600001737e3430322d747269616c320001707573682d30372d32322d72313000010112 [400] Errors [ Message[Invalid Value supplied to API: image_data was bad. Request Id: 579665c300ff05e6c316a09e600001737e3430322d747269616c320001707573682d30372d32322d72313000010112] Location[ - ] Reason[INVALID_VALUE] Domain[global] ]
Does anyone know the correct format for the Data property of the Google.Apis.ConsumerSurveys.v2.Data.SurveyQuestionImage object?
The data needs to be base64 encoded and also "urlsafe" or "websafe" depending on what language you are using. (python and java, respectively)
In other words, you'll need to first base64 encode then:
Web safe encoding uses '-' instead of '+', '_' instead of '/'
Hope this helps!
For c# users, check out this technique for making websafe b64:
How to achieve Base64 URL safe encoding in C#?
For .net users, look at the comments in this question:
Converting string to web-safe Base64 format
And also this link for more info about .net specific options for encoding:
http://www.codeproject.com/Tips/76650/Base-base-url-base-url-and-z-base-encoding
And to specifically answer the original poster, try this for converting your byte array to a string.
public static string ToBase64ForUrlString(byte[] input)
{
StringBuilder result = new StringBuilder(Convert.ToBase64String(input).TrimEnd('='));
result.Replace('+', '-');
result.Replace('/', '_');
return result.ToString();
}
I've created a JSON string in a php file. I've then used json_encode($jsonStr) to encode the string.
$jsonStr =
"{
\"statusCode\": 0,
\"errorMsg\": \"SUCCESS\",
\"id\": $id,
\"message\": ".json_encode($message).",
\"author\": \"$author\",
\"showAfter\": \"$date\"
}";
I'm making a network call in java (Android) to get this string. My next step is to decode the string, however this doesn't seem to be working too well.
Here is a sample of what I'm trying to decode in my Android code:
{\n\t\t\t\t\"statusCode\": 0,\n\t\t\t\t\"errorMsg\": \"SUCCESS\",\n\t\t\t\t\"id\": 1,\n\t\t\t\t\"message\": \"This is a message.\",\n\t\t\t\t\"author\": \"Anonymous\",\n\t\t\t\t\"showAfter\": \"2013-06-18 01:19:49\"\n\t\t\t}
Yes it is riddled with encoded line breaks and such. I assumed that might be the issue so I took those out, however I still have issues, so I'm guessing there must be something bigger going on.
I know this is valid JSON because I'm able to decode it and use it in a javascript based website.
How can I accomplish this on Android/Java?
Your original JSON string (the one you show in your first snippet) looks to be valid JSON already. You must not encode it. Encoding it is what makes it invalid JSON, transforming every tab into \t, and every new line into \n.
Read the documentation of json_encode carefully.
I m trying to match java base64 code in php. But getting inconsistent result.
Java base64 encode
encMessage = URLEncoder.encode(new Base64(-1).encodeToString(encrypted),"UTF8");
Java decode
message = URLDecoder.decode(message,"utf8");
Above code java encode code return the string which i have to decode and decrypt in php
PHP base64 decode
$message = utf8_decode(urldecode($encrypted));
$message = base64_decode($message);
PHP encode
$encMessage = base64_encode($encrypted);
$encMessage = utf8_encode(urlencode($encMessage));
Results:
java:
KO%2F%2B%2Bzbp5z8oCdvZn62jb72kseT%2Bem8hYUZY0IuB9zo%3D
php:
KO%2F%2B%2Bzbp5z8oCdvZn62jb3CVVVXsV%2Bws2kDOmKK%2BPEc%3D
src : https://gist.github.com/944269
I had this problem between CSharp and Java, and found that URL encoding things was the culprit. What I did in my work around was basically re-encrypt the data with a newly generated public key until I got one that didn't need URL encoding. Not a great solution, but it works, it averages 2 tries to get it right, but I've seen it taking up to 15 tries to do it, either way we're still talking milliseconds, and it works reliably.
YMMV
I've been writing a Web Application recently that interacts with iPhones. The iPhone iphone will actually send information to the server in the form of a plist. So it's not uncommon to see something like...
<key>RandomData</key>
<data>UW31vrxbUTl07PaDRDEln3EWTLojFFmsm7YuRAscirI=</data>
Now I know this data is hashed/encrypted in some fashion. When I open up the plist with an editor (Property List Editor), it shows me a more "human readable" format. For example, the data above would be converted into something like...
<346df5da 3c5b5259 74ecf683 4431249f 711630ba 232c54ac 9bf2ee44 0r1c8ab2>
Any idea what the method of converting it is? Mainly I'm looking to get this into a Java String.
Thanks!
According to our friends at wikipedia, the <data> tag contains Base64 encoded data. So, use your favorite Java "Base64" class to decode (see also this question).
ps. technically, this is neither "hashed" nor "encrypted", simply "encoded". "Hashed" implies a one-way transformation where multiple input values can yield the same output value. "Encrypted" implies the need for a (usually secret) "key" to reverse the encryption. Base64 encoding is simply a way of representing arbitrary binary data using only printable characters.
After base64 decoding it you need to hex encode it. This is what PL Editor is showing you.
So...
<key>SomeData</key>
<data>UW31ejxbelle7PaeRAEen3EWMLojbFmsm7LuRAscirI=</data?
Can be represented with...
byte[] bytes = Base64.decode("UW31ejxbelle7PaeRAEen3EWMLojbFmsm7LuRAscirI=");
BigInteger bigInt = new BigInteger(bytes);
String hexString = bigInt.toString(16);
System.out.println(hexString);
To get...
<516df5aa 3c5b5259 74ecf683 4401259f 711630ba 236c59ac 9bb2ee44 0b1c8ab2>