I'm developing an android App that collect some data from 4 sensors via Bluetooh and at the end send the data to a SFTP server.
I'm using the JSCh (ChannelSftp), the thing works fine with some servers, but with the server of my University the App crash.
I have performed a deep debug with the IT officer and we discovered that once the SSH channel is open some background traffic arrives to the server (ex.: myIP --- otherIP--- packet). At that point the firewall close the connection and the App crash.
Is there a way to block the background traffic for a small window of time from the App?. Has anyone had the same problem as me?
Thanks in advance
public class SftpClass extends AsyncTask <Object, Void, String> {
private Context context;
private long size;
private long fileSize;
public SftpClass (Context con){
context = con;
size = 0;
fileSize = -1;
}
#Override
protected String doInBackground(Object... params){
//Params: File file, String host, String port, String username, String password
File file = (File) params[0];
String host = (String) params[1];
String port = (String) params[2];
String username = (String) params[3];
String password = (String) params[4];
String path = (String) params[5];
int portnumber = Integer.valueOf(port);
fileSize = file.length();
String localFilePath = file.getAbsolutePath();
String fileName = localFilePath.substring(localFilePath.lastIndexOf("/") + 1);
String remoteFilePath = fileName;
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, portnumber);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
final ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(localFilePath, path+remoteFilePath);
try
{
Thread.sleep(3000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
SftpATTRS attrs = null;
try {
attrs = sftpChannel.lstat(path+remoteFilePath);
} catch (SftpException e) {
e.printStackTrace();
}
if ( attrs != null){
size = attrs.getSize();
}
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
if (size == fileSize){
Toast.makeText(context, "File uploaded\n"+Long.toString(size)+"Bytes", Toast.LENGTH_SHORT).show();
}
}
}
Related
I'm using JavaMail libraries to access Gmail and I'm getting a slow rate (Rx) performance in downloading a compressed file attachment (1 MB):
As you can see, getting the attachment and write it into SD takes around 20 seconds.
Here is my code:
public class MailFile {
InputStream is;
String fileName;
public MailFile( InputStream is, String fileName) {
this.is = is;
this.fileName = fileName;
}
public InputStream getIs() {
return is;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}}
Retrieving a message:
private List<MailFile> getAttachments(Message temp) throws Exception {
List<MailFile> attachments = new ArrayList<MailFile>();
Multipart multipart = (Multipart) temp.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (bodyPart.getFileName()!=null && (bodyPart.getFileName().contains(ZIP_EXT) || bodyPart.getFileName().contains(XLSX_EXT)))
attachments.add(new MailFile(bodyPart.getInputStream(), bodyPart.getFileName()));
}
return attachments;
}
protected String doInBackground(String... params) {
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
Properties props = new Properties();
//IMAPS protocol
props.setProperty("mail.store.protocol", "imaps");
//Set host address
props.setProperty("mail.imaps.host", "imaps.gmail.com");
//Set specified port
props.setProperty("mail.imaps.port", "993");
//Using SSL
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.partialfetch", "false"); //this line solved my problem
Session imapSession = Session.getInstance(props);
Store store = imapSession.getStore("imaps");
store.connect("imap.gmail.com", SP.getString("incomingMail", activity.getString(R.string.confIncomingDefaultValue)), SP.getString("passwordMail", activity.getString(R.string.confIncomingDefaultValue)));
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
Message msgArr[] = inbox.search(this.searchTerm);
//Message msg = inbox.getMessage(inbox.getMessageCount());
if (msgArr.length > 0) {
Message msg = msgArr[msgArr.length - 1]; //only last message
Object content = msg.getContent();
if (content instanceof Multipart) //si és un correu amb attach
{
Multipart mp = (Multipart) content;
for (MailFile f : getAttachments(msg)) {
if (f.getFileName().contains(XLSX_EXT)) {
new XLSXReader(f.getIs());
// msg.setFlag(Flags.Flag.DELETED, true);
} else if (f.getFileName().contains(ZIP_EXT)) {
long startTime = System.currentTimeMillis();
writeToFile(f.getIs(),new FileOutputStream(f.getFileName()));
long duration = System.currentTimeMillis() - startTime;
Log.d("Time", "Time " + duration + "ms " + duration / 1000.0f + " sec");
ZipperFolders.unzipFile(unzipPath, f.getFileName());
loadZipObjects(f.getFileName());
}
}
doToast(activity.getString(R.string.messagesReceivedOK));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((PrincipalActivity) activity).setDate(null, false);
}
});
} else
doToast(activity.getString(R.string.messagesReceivedKO));
} else
doToast(activity.getString(R.string.messagesNoneMessages, SP.getString("incomingMail", activity.getString(R.string.confIncomingDefaultValue))));
inbox.close(true);
store.close();
} catch (Exception e) {
e.printStackTrace();
doToast(activity.getString(R.string.messagesConnectionKO));
}
return activity.getString(R.string.messagesReceived);
}
I've tried to use MimeMessage but the result it's the same. If I donwload the same file inside the Gmail app it takes 2 seconds!. What's happening? Is Gmail limiting my bandwith? Am I doing something wrong? Thanks!
EDIT: I've solved myproblem adding props.setProperty("mail.imaps.partialfetch", "false"); before declaring the Session object.
This is the resultant Rx:
From 20 sec. to 2 sec. unbelievable!!
I am working on GCM.
I am able to send notifications to all registered android devices from my local server.
I have saving regid and userid in database. my requirement is send notifications to particular devices.how to do that?
am using java on server side. Any answers will save me..i posted server side code
server side code
public class GCMNotification extends HttpServlet {
private static final long serialVersionUID = 1L;
// Put your Google API Server Key here
private static final String GOOGLE_SERVER_KEY = "AIzaSyDzlDr2viv-EghBFZGpjwXcDoqh24Wt9yE";
static final String MESSAGE_KEY = "message";
static final String TITLE_KEY = "title";
static final String IMAGE_KEY= "image";
static final String ORDER_KEY= "order";
private List<String> androidTargets = new ArrayList<String>();
public GCMNotification() {
super();
// androidTargets.add(re);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//doPost(request, response);
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
String sql;
sql = "SELECT regid, fname, email FROM my_db.Persons";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("regid");
String first = rs.getString("fname");
String last = rs.getString("email");
androidTargets.add(id);
}
rs.close();
stmt.close();
con .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
//MulticastResult result = null;
//Result result1=null;
Writer writer=null;
Connection con=null;
PrintWriter out = response.getWriter();
String share = request.getParameter("shareRegId");
// GCM RedgId of Android device to send push notification
String reg = "";
String emailId="";
String fname="";
if (share != null && !share.isEmpty()) {
reg = request.getParameter("regId");
emailId=request.getParameter("email");
fname=request.getParameter("name");
System.out.println("regId: " + reg);
System.out.println("mailid " + emailId);
System.out.println("name "+ fname);
try {
//Load the Driver for connection
Class.forName("com.mysql.jdbc.Driver");
//Get a connection to the particular database
con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_db","root","root1");
PreparedStatement pst=con.prepareStatement("insert into my_db.Persons(regid,email,fname) values(?,?,?)");
pst.setString(1,reg);
pst.setString(2,emailId);
pst.setString(3,fname);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MulticastResult result1=null;
String userMessage = request.getParameter("message");
String imageUrl = request.getParameter("image");
String order1=request.getParameter("odt");
String titl=request.getParameter("tit");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(10000)
.delayWhileIdle(false)
.addData(TITLE_KEY, titl)
.addData(MESSAGE_KEY,userMessage)
.addData(IMAGE_KEY, imageUrl)
.addData(ORDER_KEY, order1)
.build();
try {
// use this for multicast messages. The second parameter
HashSet<String> set = new HashSet<String>(androidTargets);
// Create ArrayList from the set.
ArrayList<String> result = new ArrayList<String>(set);
System.out.println("reg2:"+result);
// of sender.send() will need to be an array of register ids.
result1 = sender.send(message, result,1);
/* if (result1.getResults() != null) {
int canonicalRegId = result1.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result1.getFailure();
System.out.println("Broadcast failure: " + error);
}*/
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("pushStatus", result1.toString());
request.getRequestDispatcher("index.jsp")
.forward(request, response);
}
}
Simply add a where clause to your sql query to filter out the exact user you want to deal with. If you want to filter the user by the email then use something like this..
sql = "SELECT regid, fname, email FROM my_db.Persons where email = 'abc#gmail.com'";
I am trying to write an app that sends a string to a specified IP address and Port number. The destination already has a server that accepts strings, but for some reason, the app cannot establish a socket with the server, it keeps timing out. I have only written code, so if I have to do something else like port forward on either the client or server end, please let me know.
The goal of this app is to take in a string for an IP address, a string for the Port number, and a String for the message to send to the destination. After pressing the Send button, the app will send the message to the IP and Port number defined, and display a response from the server.
This also will be used in two applications: once between the Android App and a Python server, and other between the Android App and custom hardware. Hopefully there is a solution to fit both cases.
Client Code:
public static class PlaceholderFragment extends Fragment {
TextView recieve;
EditText addressText, portText, messageText;
Button send;
Socket socket = null;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_customize_gateway, container, false);
recieve = (TextView) rootView.findViewById(R.id.textView1);
addressText = (EditText) rootView.findViewById(R.id.editText1);
portText = (EditText) rootView.findViewById(R.id.editText2);
messageText = (EditText) rootView.findViewById(R.id.editText3);
send = (Button) rootView.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncSend aSend= new AsyncSend(addressText.getText().toString(),Integer.parseInt(portText.getText().toString()), messageText.getText().toString());
aSend.execute();
}
});
return rootView;
}
public class AsyncSend extends AsyncTask<Void, Void, Void> {
String address;
int port;
String message;
String response;
AsyncSend(String addr, int p, String mes) {
address = addr;
port = p;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
Socket socket = null;
try {
System.out.println("Test");
socket = new Socket(address, port);
System.out.println("Test");
DataOutputStream writeOut = new DataOutputStream(socket.getOutputStream());
writeOut.writeUTF(message);
writeOut.flush();
ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream writeIn = socket.getInputStream();
while((bytesRead = writeIn.read(buffer)) != -1) {
writeBuffer.write(buffer,0,bytesRead);
response += writeBuffer.toString("UTF-8");
}
} catch (UnknownHostException e){
e.printStackTrace();
response = "Unknown HostException: " + e.toString();
System.out.println(response);
} catch (IOException e) {
response = "IOException: " + e.toString();
System.out.println(response);
} finally {
if (socket != null) {
recieve.setText(response);
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recieve.setText(response);
super.onPostExecute(result);
}
}
}
Server Code:
import http.server
import socket
import threading
import socketserver
import pymongo
import smtplib
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
#Connect to database
try:
from pymongo import MongoClient
dbclient = MongoClient()
db = dbclient.WDI_database
print("Database Connected")
except pymongo.errors.ConnectionFailure as e:
print("Database Failed: {}".format(e))
col = db.users
data2 = str(self.request.recv(1024), 'ascii')
print("Server: {}".format(data2));
data = data2.split("||")
username, password, camunits, homunits = data[0], data[1], data[2], data[3]
post = {"user": username,
"pass": password,
"cam": camunits,
"disp": homunits}
col.insert(post)
print(col.count())
cur_thread = threading.current_thread()
response = bytes("{} Received data for: {}".format(cur_thread, username), 'ascii')
self.request.sendall(response)
class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print("Recieved: " + data.decode("utf-8"))
socket.sendto(data.upper(), self.client_address)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "", 5000
tcpserver = ThreadedTCPServer((HOST, PORT-1), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=tcpserver.serve_forever)
server_thread.daemon = True
server_thread.start()
print("TCP serving at port", PORT-1)
while True:
pass
tcpserver.shutdown()
Using the Socket class is too low-level for your purposes and fraught with potential gotcha's. I suggest using org.apache.http.client.HttpClient instead.
It was probably because I didn't port forward, so my connection got blocked by my router. I opened the port on both the router and Windows.
I am sending a String from an Android device to a python server via TCP socket, but when the message arrives on the server, there are extra characters in the front. For example, if I send the string
asdf
the result on the server would be
\x00\x13asdf
Anyone know why these characters are added to the front of the string? Is there a way to avoid this, or should I just cut these out at the server end?
For the reverse, the server sends
fdsa
The Android client receives
Nullfdsa
Client Code (Written in Android, Java):
public static class PlaceholderFragment extends Fragment {
TextView recieve;
EditText addressText, portText, messageText;
Button send, test;
Socket socket = null;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_customize_gateway, container, false);
recieve = (TextView) rootView.findViewById(R.id.textView1);
addressText = (EditText) rootView.findViewById(R.id.editText1);
portText = (EditText) rootView.findViewById(R.id.editText2);
messageText = (EditText) rootView.findViewById(R.id.editText3);
send = (Button) rootView.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncTCPSend tcpSend= new AsyncTCPSend(addressText.getText().toString(),Integer.parseInt(portText.getText().toString()), messageText.getText().toString());
tcpSend.execute();
}
});
return rootView;
}
public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
String address;
int port;
String message;
String response;
AsyncTCPSend(String addr, int p, String mes) {
address = addr;
port = p;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 4999);
DataOutputStream writeOut = new DataOutputStream(socket.getOutputStream());
writeOut.writeUTF(message);
writeOut.flush();
ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream writeIn = socket.getInputStream();
while((bytesRead = writeIn.read(buffer)) != -1) {
writeBuffer.write(buffer,0,bytesRead);
response += writeBuffer.toString("UTF-8");
}
response = response.substring(4); //Server sends extra "Null" string in front of data. This cuts it out
} catch (UnknownHostException e){
e.printStackTrace();
response = "Unknown HostException: " + e.toString();
System.out.println(response);
} catch (IOException e) {
response = "IOException: " + e.toString();
System.out.println(response);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
recieve.setText(response);
super.onPostExecute(result);
}
}
Server Code (In Python):
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
#Connect to database
try:
from pymongo import MongoClient
dbclient = MongoClient()
db = dbclient.WDI_database
print("Database Connected")
except pymongo.errors.ConnectionFailure as e:
print("Database Failed: {}".format(e))
col = db.users
data2 = str(self.request.recv(1024), 'utf-8')
print("Server: {}".format(data2));
data = data2.split("||")
try:
#[2:] because we get two extra symbols in front of the username from Android
username = data[0][2:]
except IndexError:
username = ""
try:
password = data[1]
except IndexError:
password = ""
try:
camunits = data[2]
except IndexError:
camunits = 0
try:
homunits = data[3]
except IndexError:
homunits = 0
post = {"user": username,
"pass": password,
"cam": camunits,
"disp": homunits}
col.insert(post)
print(col.count())
response = bytes("Received data for: {}".format(username), 'utf-8')
self.request.sendall(response)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = "", 5000
tcpserver = ThreadedTCPServer((HOST, PORT-1), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=tcpserver.serve_forever)
server_thread.daemon = True
server_thread.start()
print("TCP serving at port", PORT-1)
while True:
pass
tcpserver.shutdown()
I think I got some explanations about the extra characters.
In the java code, you are not getting an extra "Null" from the socket, the response string variable is not initialized, by default it is null, and you say response += writeBuffer.toString("UTF-8"); so you append something to a null string, which happened to be "null" + something.
I would initialize the variable in the declaration or just before the while loop:
String response = "";
In the Phyton code, I see nothing wrong, therefore I'd suggest you to write what you send to the Log and see if the extra characters are in the bytes you send.
Instead of writeOut.writeUTF(message);
try socket.getOutputStream().write(message.getBytes()); // UTF-8 is the default.
and write it to the Log:
android.util.Log.w("SENT", String.format("[%s] %d", message, message.length()));See the log to find out what you're really sending.
Let java send the extra character. It did in my case too.
I used -
data2 = data.strip()
if data2 == "(your desired data)"
//execution instructions
and so on.
i did a simple Web Service in Java and i deployed it in JBOSS 5.1.
This WS handles C2DM service for sending a notify message to an Android phone. I set all like i red in google c2dm api, and, first of all, i sign up for accessing to c2dm service. In this case, all works well.
Now i have to do the same in .NET on IIS7. Some clarification about the .Net code:
setRegId() and pushMessage() method are available by WebService.
handShakeRegId() is simply called by setRegId() after String "reg_id" and "device_id" are setted
all code commented are my try for solving problem, but all was useless
Thats the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace WebService1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
private String accountType = "HOSTED_OR_GOOGLE";
private String email = "example#gmail.com";
private String password = "password";
private String service = "ac2dm";
private String source = "com.cloudTest.app";
private String HTTPHeaderCT = "application/x-www-form-urlencoded";
private String auth;
private String reg_Id;
private String deviceId;
private String collapseKey = "CollapseKey";
public void handShakeRegId()
{
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create(#"https://www.google.com/accounts/ClientLogin");
// string proxy = null;
// req.MaximumAutomaticRedirections = 4;
// req.MaximumResponseHeadersLength = 4;
// req.Credentials = CredentialCache.DefaultCredentials;
string data = String.Format("accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}", accountType, email, password, service, source);
byte[] buffer = Encoding.UTF8.GetBytes(data);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.WriteLine("--------------------");
Debug.Write("(handShakeRegId) Request Error:" + e);
Debug.WriteLine("--------------------");
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst, Encoding.UTF8);
string response = sr.ReadToEnd();
string SID = response.Substring((response.IndexOf("SID=") + 4),
(response.IndexOf("\n") - 4));//extracting SID
string Auth = response.Substring((response.IndexOf("Auth=") + 5),
(response.Length - (response.IndexOf("Auth=") + 5)) - 1);//extracting Auth
auth = Auth;
}
catch (Exception e)
{
Debug.Write("(handShakeRegId) Response Error:" + e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
[WebMethod]
public void setRegId(String reg_id, String device_id)
{
reg_Id = reg_id;
deviceId = device_id;
Debug.WriteLine("RegID=" + reg_Id);
Debug.WriteLine("--------------------");
Debug.WriteLine("DeviceID=" + deviceId);
handShakeRegId();
}
[WebMethod]
public void pushMessage(String msg)
{
// Needed! Without an SSL Exception comes out
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };
HttpWebRequest req;
Stream reqst;
try
{
req = (HttpWebRequest)WebRequest.Create("http://android.apis.google.com/c2dm/send");
//req.MaximumAutomaticRedirections = 4;
//req.MaximumResponseHeadersLength = 4;
//req.Credentials = CredentialCache.DefaultCredentials;
//req.Credentials = new NetworkCredential("example#gmail.com","password");
//req.KeepAlive = true;
//string proxy = null;
string data = String.Format("registration_id={0}&collapse_key={1}&data.message={2}", reg_Id, collapseKey, msg);
// ASCIIEncoding encoding = new ASCIIEncoding();
// byte[] buffer = encoding.GetBytes(data);
byte[] buffer = Encoding.UTF8.GetBytes(data);
req.Method = "POST";
req.ContentType = HTTPHeaderCT;
req.ContentLength = buffer.Length;
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
// req.Proxy = new WebProxy(proxy, true);
// req.CookieContainer = new CookieContainer();
reqst = req.GetRequestStream(); // add form data to request stream
reqst.Write(buffer, 0, buffer.Length);
}
catch (Exception e)
{
Debug.Write("(PushMessageMsgOUT)Error: " + e);
throw;
}
HttpWebResponse res;
Stream resst;
try
{
res = (HttpWebResponse)req.GetResponse();
HttpStatusCode responseCode = ((HttpWebResponse)res).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
Debug.WriteLine("Unauthorized - need new token");
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
Debug.WriteLine("Response from web service not OK :");
Debug.WriteLine(((HttpWebResponse)res).StatusDescription);
}
resst = res.GetResponseStream();
StreamReader sr = new StreamReader(resst);
string response = sr.ReadToEnd();
}
catch (Exception e)
{
Debug.WriteLine("(pushMessageMsgIN) Error: "+e);
throw;
}
resst.Flush();
resst.Close();
reqst.Flush();
reqst.Close();
}
}
}
Handshake method works well! I get auth token without problem.
setRegId method is called by Android device (in my case is the Android+GoogleApi 2.2 emulator)
Error which comes out is always the same in pushMessage getResponse() ( and its strange because i implement connection exactly like its in handshake method :-/ ):
A first chance exception of type 'System.Net.WebException' occurred in System.dll
(pushMessageMsgIN) Error: System.Net.WebException: remote server error (401) Unauthorized in System.Net.HttpWebRequest.GetResponse()
2 days for searching something useful but.... NOTHING!!
Its very stressful...
I hope someone can help me.
I red something about Authentication in IIS, so i enabled Anonymous User and other unknown things just for trying. Nothing!
Solved: MY STUPIDITY !!! i made a mistake in private String source !! I specified a wrong package name! -.-