I got notification from FCM of google, but my messageBody was garbled. How to resolve it? - google-cloud-messaging

Post was successful, but the message body was garbled.
{"data":{"data_content":"測試","data_title":"Joyce"},"notification":{"body":"測試","title":"test"},"to":"myDeviceId"}
this.is my post code , is there any wrong? Thanks.
<pre><code>
public class HttpConnection {
public void startConnection(final String apiUrl, final String jsonStr, final OnPostNotificationListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
StringBuilder response = new StringBuilder();
try {
URL url = new URL(apiUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","key=Key");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
OutputStream os = conn.getOutputStream();
DataOutputStream writer = new DataOutputStream(os);
writer.writeBytes(jsonStr);
writer.flush();
writer.close();
os.close();
//Get Response
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
listener.onSuccessful(response.toString());
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
listener.onFail(ex.toString());
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
public interface OnPostNotificationListener{
void onSuccessful(String result);
void onFail(String exception);
}
}
</code></pre>
Thank you for your help.The picture of the phone

The problem comes from writeBytes method and the representation of kanjis (or other non ISO-8859-1 characters). You should use writeUTF method instead :
writer.writeUTF(jsonStr);
You can take a look at this post explaning the difference between writeBytes and writeUTF. Basically, you should always use writeUTF when writing strings.

Related

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

HTTP Requests in Glass GDK

I am implementing a GDK application and need to do in my application some HTTP Post requests. Do I send the HTTP requests the same way as on android phone or there is some other way of doing it? (I have tried the code that I am using on my phone and it's not working for glass.)
thanks for your help in advance.
You can make any post request like in smartphones, but ensure you make the requests using an AsyncTask.
For example:
private class SendPostTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Make your request POST here. Example:
myRequestPost();
return null;
}
protected void onPostExecute(Void result) {
// Do something when finished.
}
}
And you can call that asynctask anywhere with:
new SendPostTask().execute();
And example of myRequestPost() may be:
private int myRequestPost() {
int resultCode = 0;
String url = "http://your-url-here";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add headers you want, example:
// post.setHeader("Authorization", "YOUR-TOKEN");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "111111"));
nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
resultCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (Exception e) {
Log.e("POST", e.getMessage());
}
return resultCode;
}

Error on WP7 app WebRequest

I have this errors on 'error List'.
'ContentLength' is not a member of 'System.Net.WebRequest'
'GetRequestStream' is not a member of 'System.Net.WebRequest'
'GetResponse' is not a member of 'System.Net.WebRequest'
I'm make an App WindowsPhone 7 with vb.net on VisualStudio 2010
i can't understand why. Thanks
You can't due to the async nature of WP. It seems like you have lifted examples from a non WP project. In WP, you have to make the call and then register an even that listens to the completion of the task. Further reading on Async Calls
private void GetSource(object sender, RoutedEventArgs e)
{
System.Net.WebRequest request = WebRequest.Create("http://www.bbc.co.uk");
//request.ContentType = "application/json";
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
var request = asynchronousResult.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(asynchronousResult);
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
var responseString = reader.ReadToEnd();
MessageBox.Show(responseString);
}
}
}
catch (WebException e)
{
// Handle exception
MessageBox.Show(e.Message);
}
}
}
public void SendPost(Uri uri, string json)
{
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.UploadStringCompleted += this.sendPostCompleted;
webClient.UploadStringAsync(uri, "POST", json);
}

How to Serialize CookieContainer in wp7 applications?

I tried to Serialize cookie to save it and Deserialize at next time I start my application.But the result of Deserialize is empty.What's wrong?
void SaveCookie() {
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (this.checkBox_save_passowrd.IsChecked == true)
{
CookieContainer cc = SEC_Services.Httprequest.cookie;
string fileName = "usercookie.xml";
using (var file = appStorage.OpenFile(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
using (var writer = new StreamWriter(file))
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
xs.Serialize(writer, cc);
writer.Close();
}
}
}
else {
if (appStorage.FileExists("usercookie.xml"))
{
appStorage.DeleteFile("usercookie.xml");
}
}
}
void ReadCookie() {
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (appStorage.FileExists("usercookie.xml"))
{
using (System.IO.StreamReader reader = new StreamReader(appStorage.OpenFile("usercookie.xml", FileMode.Open)))
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
CookieContainer obj = (CookieContainer)xs.Deserialize(reader);
reader.Close();
SEC_Services.Httprequest.cookie = obj;
if (obj.Count != 0) {
NavigationService.Navigate(new Uri("/PanoramaPage.xaml", UriKind.Relative));
}
}
}
}
I also found this simple
C#: Writing a CookieContainer to Disk and Loading Back In For Use
shows that CookieContainer could be Serialize.But there is no SoapFormatter in wp7 library
IsolatedStorageSettings.ApplicationSettings["index"] = yourcookie;
So you don't need to serialize it.
I'm using it in a project
As the question is "How to Serialize CookieContainer" and the accepted answer doesn't really answer this. This is how to do it with serialization:
Write to disk:
public static void WriteCookiesToDisk(string file, CookieContainer cookieJar)
{
using(Stream stream = File.Create(file))
{
try {
Console.Out.Write("Writing cookies to disk... ");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, cookieJar);
Console.Out.WriteLine("Done.");
} catch(Exception e) {
Console.Out.WriteLine("Problem writing cookies to disk: " + e.GetType());
}
}
}
Read from disk:
public static CookieContainer ReadCookiesFromDisk(string file)
{
try {
using(Stream stream = File.Open(file, FileMode.Open))
{
Console.Out.Write("Reading cookies from disk... ");
BinaryFormatter formatter = new BinaryFormatter();
Console.Out.WriteLine("Done.");
return (CookieContainer)formatter.Deserialize(stream);
}
} catch(Exception e) {
Console.Out.WriteLine("Problem reading cookies from disk: " + e.GetType());
return new CookieContainer();
}
}