I need to upload a file through http or ftp to the website in blackberry jde.
High level view: You open an OutputStream from an HttpConnection and write your data into that output stream. The main problem is going to be choosing which network connection to use (I recommend looking at this, unless you're on OS 5.0 which has a similar feature built in). As to uploading through FTP that will be somewhat more difficult as there is no support for FTP built into the BlackBerry API instead you'll have to look at using a SocketConnection and implementing part of FTP yourself.
Here's some code to get you started:
HttpConnection httpConn = (HttpConnection) Connector.open("<URL>");
FileConnection fileConn = (FileConnection) Connector.open("file:///<path>");
InputStream in = fileConn.openInputStream();
OutputStream out = httpConn.openOutputStream();
byte[] buffer = new byte[100];
int bytesRead = 0;
while((in.read(buffer) = bytesRead) > 0)
{
out.write(buffer, 0, bytesRead);
}
Of course you'll need to deal with exceptions, close the streams, check that it was uploaded successfully, etc
Related
I am hitting the following url from my android device.
URL : https://www.googleapis.com/youtube/v3/search?key=MY_KEY&channelId=UCoWgc1mqe-bcfb_lem7EyOg&part=snippet,id&order=date&maxResults=50
Response: ������������������]�r�8�}ϯ#e?䋕�}ɗ j����%OO(#�q3���*b�a"�g�o�K��%Y]�em�,uGd8m�ātu��]������/�c���W�_����B���M��;v�������q:��fA�[8KR�����lZ?[t]�JL���`�������G1����h䬑��T[}E�y�]qt�_xl��.��e/v�o���H
For getting the YouTube Videos List.It was working fine before but sometimes its response is not valid while hitting from browsers it works well.
Please help me !!
I found the solution i was using the loop j library (for http request) old version
just changes
compile 'com.loopj.android:android-async-http:1.4.8'
to
compile 'com.loopj.android:android-async-http:1.4.9'
it solved my problem
Please see my related question here (but in C#) and the answers on it in order to understand what I mean. Then you have to search example fordecompress gzip android and look at the existing resources to accomplish this.
Please keep in mind, that the API does not always send the response in gzip-format or not. So please do a check if the response is really in gzip.
For the plain decompression you can use the following method:
public static String decompress(byte[] compressed) throws IOException {
final int BUFFER_SIZE = 32;
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis, BUFFER_SIZE);
StringBuilder s = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) {
s.append(new String(data, 0, bytesRead));
}
gis.close();
bis.close();
return s.toString();
}
(this code was taken from Vyshnavi's answer)
I want to download a file from a server via the internet with a BlackBerry app.
It is not important which protocol is used: FTP, HTTP or something else would be fine. I just need the user to click "download" button and then the app downloads this file from a server.
I have no idea how it can be done. I have tried a few solutions. In one I need a HttpConnectorFactory but this is not in my API.
I have searched for an answer to my question for days, but I haven't found a solution that works.
Links to solutions I have tried:
How to download an html file in a BlackBerry application
https://stackoverflow.com/questions/6290988/downloading-a-pdf-file-from-a-webserver-in-blackberry-java-application
Networking Helper Class
try this -
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc = connFact.getConnection(your_url);
HttpConnection httpConn = (HttpConnection) connDesc.getConnection();
try {
httpConn.setRequestMethod(HttpConnection.GET);
InputConnection inputConn = (InputConnection) httpConn;
InputStream is = inputConn.openInputStream();
byte[] data =IOUtilities.streamToBytes(is);
//the value in data will be the bytes of your file.
// now if you want to save the file, you can do it here......
} catch (IOException e) {
e.printStackTrace();
}
I am trying to consume SOAP response xml by passing request xml in a string, using BlackBerry Java plugin for Eclipse. I have been struck on this for the past two days looking for a way to solve it.
I have attached the sample code below.
public String CheckXml()
{
final String requestXml="<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><header xmlns=\"http://schemas.cordys.com/General/1.0/\"></header><SOAP:Body><authenticateAgainstOID xmlns=\"http://schemas.cordys.com/OIDAuthentication\"><stringParam>HEMANTS_MUM013</stringParam><stringParam1>TATA2012</stringParam1></authenticateAgainstOID></SOAP:Body></SOAP:Envelope>";
final String HOST_ADDRESS = "http://xyz.com/cordys/com.eibus.web.soap.Gateway.wcp?organization=o=B2C,cn=cordys,cn=cbop,o=tatamotors.com&SAMLart=MDFn+8e5dRDaRMRIwMY7nI84eEccbx+lIiV0VhsOQ7u+SKG6n5+WNB58";
String result="";
try {
HttpConnection url=(HttpConnection)Connector.open(HOST_ADDRESS);
url.setRequestProperty("Content-Type", "text/xml");
url.setRequestMethod(HttpConnection.GET);
OutputStreamWriter writer=new OutputStreamWriter(url.openOutputStream());
writer.write(requestXml);
writer.flush();
writer.close();
StringBuffer buffer1=new StringBuffer();
InputStreamReader reader=new InputStreamReader(url.openInputStream());
StringBuffer buffer=new StringBuffer();
char[] cbuf=new char[2048];
int num;
while (-1 != (num = reader.read(cbuf))) {
buffer.append(cbuf, 0, num);
}
String result1 = buffer.toString();
} catch (Exception e) {
System.out.println(e);
}
return result;
}
I think the main issue that you aren't asking http. getResponseCode(). I think BB doesn't do any interaction until you call it.
I would also be careful with this code on the real devices. Search for correct opening connection on the BlackBerries.
I noticed that you are not including the SoapAction header in the request.
SOAP Web services usually have a fixed URL, and the differents methods are selected with the SoapAction header. You can check the header by opening the WSDL in a browser and inspecting the format for the method you want to invoke.
Once you know which action to select, set it as a regular http header:
url.setRequestProperty("SOAPAction", <your action here>);
Another source of problems in your code is that you are using the old HttpConnection class that requires appending a suffix to the URL depending on the transport type (MDS, BIS, Wi-Fi, etc). You don't need to use this legacy class unless you are targeting OS 4.5 and lower. So have a look at ConnectionFactory class, which is much easier to use. It is available since OS 5.0.
I want to utilise some form of "simple" encryption that is reasonably secure but very low friction in terms of impact on development process.
Supposing I own both sides of the conversation in a client <> web service situation. My application is a windows phone/win8/silverlight/desktop app and the server is ASP.Net MVC or WebAPI.
In my mind, I want something as simple as:-
<security encryption="off|sometype|someothertype">
<privatekey>12345MyKey54321</privatekey>
</security>
as some form of configuration parameter on both the client and server. Additionally an authentication routine will return and store some form of public key.
Doing so will enable the 'encryption mode' and result in any http requests being encrypted & hashed in the selected manner using the provided keys. The end result being anything sniffed on the local, proxy or remote machines would not be able to view the data without the key and decryption method. On the server, data is decrypted using the same key before hitting controller actions.
Other than swapping out HttpRequest/WebClient calls for something like EncryptedHttpRequest and adding the appropriate hook on the MVC/WebAPI side of things, all other client code and controller actions would be ignorant to the fact the data was encrypted.
Am I missing something or could setup not be this simple? As far as I have searched there is nothing that offers this level of simplicity so I figure I'm missing some gaping flaw in my logic?
All you are looking for can be achieved by simply using HTTPS. Just buy a certificate (or use a self-signed certificate) and there is your encryption.
Do not re-invent the wheel.
I've done this successfully. It isn't too difficult and works well. I use it for activating a license for a product. The most important thing is that your truly control the client and server - no one can extract your private key from your code on the client.
Step 1: Create an MVC controller action method that takes no arguments:
[HttpPost] public ActionResult Activate() { ... }
Step 2: In the controller just use the HttpRequest.InputStream to get ahold of the bytes sent from the client.
var stream = this.HttpContext.Request.InputStream;
Step 3: Create a CryptoStream to deserialize.
I've included creating both encryption and decryption examples here. The sharedSecret is a byte[] of sufficient length (512 bytes) of random bytes - this is what you protect!
public CryptoStream CreateEncryptionStream(Stream writeStream)
{
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
PasswordDeriveBytes derivedBytes = new PasswordDeriveBytes(this._sharedSecret, null);
CryptoStream cryptoStream = new CryptoStream(writeStream, cryptoProvider.CreateEncryptor(derivedBytes.GetBytes(16), derivedBytes.GetBytes(16)), CryptoStreamMode.Write);
return cryptoStream;
}
public CryptoStream CreateDecryptionStream(Stream readStream)
{
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
PasswordDeriveBytes derivedBytes = new PasswordDeriveBytes(this._sharedSecret, null);
CryptoStream cryptoStream = new CryptoStream(readStream, cryptoProvider.CreateDecryptor(derivedBytes.GetBytes(16), derivedBytes.GetBytes(16)), CryptoStreamMode.Read);
return cryptoStream;
}
Step 4: Use your CryptoStream another stream reader to decrypt.
I use an XmlReader so that all my existing serialization code can work either in the clear (when reading/writing to disk or database on the server) or encrypted (when transmitting).
using (var reader = XmlReader.Create(decryptionStream, settings)) { ... }
Step 5: Formulate a secure response in your controller.
This is doing the reverse of Steps 1-4 to encrypt your response object. Then you just write your encrypted response to a memory stream and return it as a File result. Below, I've shown how I do this for my license response object.
var responseBytes = GetLicenseResponseBytes(licenseResponse);
return File(responseBytes, "application/octet-stream");
private byte[] GetLicenseResponseBytes(LicenseResponse licenseResponse)
{
if (licenseResponse != null)
{
using (MemoryStream memoryStream = new MemoryStream())
{
this._licenseResponseSerializer.Write(memoryStream, licenseResponse);
return memoryStream.ToArray();
}
}
return null;
}
Step 6: Implement your client request response.
You can use HttpWebRequest or the WebClient classes to formulate the request. Here's a couple of examples from the code I use.
byte[] postBytes = GetLicenseRequestBytes(licenseRequest);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(licenseServerUrl);
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.Proxy = WebRequest.DefaultWebProxy;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
return request;
private LicenseResponse ProcessHttpResponse(HttpWebResponse response)
{
if ((response.StatusCode == HttpStatusCode.OK) && response.ContentType.Contains("application/octet-stream"))
{
var stream = response.GetResponseStream();
if (stream != null)
{
var licenseResponse = this._licenseResponseSerializer.Read(stream);
return licenseResponse;
}
}
return new LicenseResponse(LicensingResult.Error);
}
Summary and Tips
Use the streams in the request/responses on the client and server to communicate binary octet-stream data
Use CryptoStream along with an encryption algorithm (consider using the strongest encryption possilbe) and a good private key to encrypt data when you serialize/deserialize it.
Make sure to check the size and format all incoming data to the client and server (avoid buffer overruns and throw exceptions early)
Protect your private key on your client using obfuscation if possible (take a look at the DeepSea obfustactor)
I am trying to build a simple application for testing purpose in which I am making a simple Http connection .The code is running perfectly on the simulator but when I am testing the app on the real device it is not returning any response code. I think there is some error in http connection .
Here is the code that I am using for http connection:
httpConnection = (HttpConnection)Connector.open("http://www.google.com");
The device that I am using is Blackberry 8520 v5.0.0.592
Also give me some tips on how to do the debuging of any app from real device using eclipse plugin.
Thanks in advance.
If it is enough that your program works with OS 5.0+, then try using Network API:
ConnectionFactory f = new ConnectionFactory();
ConnectionDescriptor descr = f.getConnection("http://www.google.com");
HttpConnection connection = (HttpConnection) descr.getConnection();
That piece of code tries to use the first available connection type. You can fine tune it if you want.
Regarding debugging, just install BlackBerry Desktop Software, connect your 8520 with the USB cable and from eclipse, click Run -> Debug As... -> BlackBerry Device.
The connection factory worked perfectly on the new devices, but didn't work with some of the older ones like the curve and bold. This is what solved it for me:
BrowserField browserField = new BrowserField();
BrowserFieldRequest Req = new BrowserFieldRequest("http://www.yourserver.com/");
InputStream inputStream = browserField.getConnectionManager().makeRequest(Req).openInputStream();
Try to redirect the link using following code:
HttpConnection hc = (HttpConnection) Connector.open(url1);
hc.setRequestMethod(HttpConnection.GET);
hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
InputStream is = null;
String location =hc.getHeaderField("Location");
HttpConnection hcc = (HttpConnection) Connector.open(location);
is = hcc.openDataInputStream();
Try to add transport to address
For example for connect via wi-fi :
httpConnection = (HttpConnection)Connector.open("http://www.google.com;interface=wifi");