My server receive some TCP/IP data and response to client:
private static void startClient(TcpClient clientSocket)
{
NetworkStream networkStream = null;
DateTime fecha = DateTime.Now;
try
{
clientSocket.NoDelay = true;
networkStream = clientSocket.GetStream();
string receiveData = readData(clientSocket);
string responseData = "abc"; //ProcessData(receiveData);
if (responseData != null)
writeData(networkStream, responseData);
}
catch (SocketException e)
{
throw;
}
finally
{
networkStream.Close();
}
}
private static string readData(TcpClient tcpClient)
{
try
{
var bytesFrom = new byte[tcpClient.ReceiveBufferSize];
StringBuilder dataFromClient = new StringBuilder();
int readCount;
while ((readCount = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize)) != 0)
{
dataFromClient.Append(Encoding.ASCII.GetString(bytesFrom, 0, readCount));
}
//int bytesRead = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize);
//string dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
return dataFromClient.ToString();
}
catch (SocketException e)
{
throw;
}
}
private static void writeData(NetworkStream networkStream, string dataToClient)
{
Byte[] sendBytes = null;
try {
sendBytes = Encoding.ASCII.GetBytes(dataToClient);
networkStream.Write(sendBytes,0, sendBytes.Length);
networkStream.Flush();
}
catch(SocketException e)
{
throw;
}
}
With this solution the client never receives the response sent:
http://postimg.org/image/6srtslf2f/
However changing the reception to a single call to NetworkStream.Read ...
private static string readData(TcpClient tcpClient)
{
try
{
var bytesFrom = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = tcpClient.GetStream().Read(bytesFrom, 0, tcpClient.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, bytesRead);
return dataFromClient.ToString();
}
catch (SocketException e)
{
throw;
}
}
... the client receives the response
http://postimg.org/image/uih9hadfr/
UPDATE
I found solution here. I´ve fixed it using 2/3 ways described . First handle EOS end message. Seccond is setting receive timeout if client works bad and sends bad data without EOS:
private static string readData(TcpClient tcpClient)
{
var clientStream = tcpClient.GetStream();
var dataFromClient = string.Empty;
var buffer = new byte[RECEIVE_BUFFER_SIZE];
if (!clientStream.CanRead)
return "";
tcpClient.ReceiveTimeout = RECEIVE_TIMEOUT;
try
{
int readCount;
while ((readCount = clientStream.Read(buffer, 0, buffer.Length)) != 0)
{
dataFromClient += Encoding.ASCII.GetString(buffer, 0, readCount);
if (dataFromClient.EndsWith(EOS))
return dataFromClient;
}
return dataFromClient.ToString();
}
catch (Exception ex)
{
var socketExept = ex.InnerException as SocketException;
if (socketExept != null && socketExept.SocketErrorCode == SocketError.TimedOut)
Logger.Warn(string.Format("Se excedio el timeout de recepcion: {0} ms",RECEIVE_TIMEOUT));
else
Logger.Error(string.Format("Error leyendo el mensaje recibido"), ex);
return dataFromClient.ToString();
}
}
Related
Returning answer is too long, but I wait until I see how much my Thread.Sleep(). What should I do to see them all? instead of Thread.Sleep(100)
if (NetworkInterface.GetIsNetworkAvailable())
{
TcpClient tcpCli = new TcpClient();
bool connectionStatus = GetConnection(ipAddress, tcpPort, out tcpCli);
NetworkStream stream = null;
if (connectionStatus == false)
return "Could not establish TCP connection";
else
{
try
{
//Send data to TCP Client
Byte[] data = Encoding.ASCII.GetBytes(SendData);
stream = tcpCli.GetStream();
stream.Write(data, 0, data.Length);
//Thread.Sleep(100);
//Read data from TCP Client
data = new Byte[tcpCli.ReceiveBufferSize];
Int32 bytes = stream.Read(data, 0, data.Length);
string answer = Encoding.ASCII.GetString(data, 0, bytes);
if (answer.Contains("**"))
return answer;
else
return "Panel no answer";
}
catch (Exception) { return "COMMUNICATION ERROR"; }
finally { tcpCli.Close(); }
}
}
I solved it that way. maybe it could help someone.
public static string TcpPanelGetSet(string ipAddress, int tcpPort, string SendData, string finishValue)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
TcpClient tcpCli = new TcpClient();
bool connectionStatus = GetConnection(ipAddress, tcpPort, out tcpCli);
NetworkStream stream = null;
if (connectionStatus == false)
return "Could not establish TCP connection";
else
{
try
{
//Send data to TCP Client
Byte[] data = Encoding.ASCII.GetBytes(SendData);
stream = tcpCli.GetStream();
stream.Write(data, 0, data.Length);
//Read from TCP Client
string answer = "";
DateTime st = DateTime.Now;
DateTime et = DateTime.Now.AddSeconds(300);
do
{
st = DateTime.Now;
if (st > et)
return "TIME-OUT";
data = new Byte[tcpCli.ReceiveBufferSize];
Int32 bytes = stream.Read(data, 0, data.Length);
string tmpAnswer = Encoding.ASCII.GetString(data, 0, bytes);
if (tmpAnswer.Contains(finishValue))
{
answer += tmpAnswer;
break;
}
answer += tmpAnswer;
} while (et > st);
if (answer.Contains("**"))
return answer;
else
return "Panel no answer";
}
catch (Exception) { return "COMMUNICATION ERROR"; }
finally { tcpCli.Close(); }
}
}
else
{
return "THERE IS NO CONNECTION";
}
}
I am developing a Windows phone 8 app that needs to upload photos to amazon s3 storage. However, I find that this is impossible since the HttpClient time out after about 60 seconds regardless of what timeout setting I use.
Is there really no way to upload large files from Windows Phone?
BackgroundTransferRequest is useless since it cannot send the neccessary metadata with file uploads.
I use this code (which times out):
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(30);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, m_uploadUrl);
httpContent.Headers.Add("Keep-Alive", "true");
request.Content = httpContent; // 3-5 Mb file
response = await httpClient.SendAsync(request);
statusCode = response.StatusCode;
}
I also tried PostAsync(), but same result. After about 60 sec the call completes with a status code 400 or 404. This is not a server timeout. IPhone and Android apps use the same service. No problems there.
Any ideas on how to upload files that takes more than 60 seconds to send?
I too faced similar things. The timeout glitch.
Check if you could use another class instead of HttpClient.
WebClient may be.
Check if this helps you:
http://blog.anthonybaker.me/2013/06/how-to-upload-file-from-windows-phone.html
and even this:
http://chriskoenig.net/2011/08/19/upload-files-from-windows-phone/
I got things working for me with those.
I've used several days now to implement a new uploader and get all the details working. I used HttpWebRequest with the async methods and split the file into chuncks. Finally I got it working and it uploads without the timeout. Here is the complete code:
using System;
using Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Services
{
public class UploadData
{
public Stream PostStream { get; set; }
public Stream FileStream { get; set; }
public byte[] HeaderBytes {get; set;}
public byte[] FooterBytes {get; set;}
public byte[] Buffer { get; set; }
public Photo Upload { get; set; }
public int BytesWritten { get; set; }
}
public class UploadEventArgs : EventArgs
{
public Photo Upload { get; set; }
public int Progress { get; set; }
}
public class UploadService
{
public delegate void CompletedEventHandler(object sender, UploadEventArgs e);
public event CompletedEventHandler UploadCompleted;
public delegate void ProgressEventHandler(object sender, UploadEventArgs e);
public event ProgressEventHandler ProgressChanged;
private static string contentType = "multipart/form-data; boundary={0}";
private static string headerString = "Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: Content-Type: application/octet-stream\r\n\r\n";
private HttpWebRequest m_request;
private static string boundarystr;
private UploadData m_uploadData;
private bool m_isStopped;
public async Task StartUpload(Photo upload, Uri uri, Dictionary<string, string> parameters)
{
try
{
m_isStopped = false;
var fileStream = (await upload.File.OpenReadAsync()).AsStreamForRead();
var uploadData = new UploadData();
boundarystr = "---------------------------" + DateTime.Now.Ticks.ToString("x");
string para = GetParamsString(parameters);
string headAndParams = para + String.Format(headerString, HttpUtility.UrlEncode(upload.File.Name));
var headerBytes = System.Text.Encoding.UTF8.GetBytes(headAndParams);
var footerBytes = Encoding.UTF8.GetBytes("\r\n--" + boundarystr + "--\r\n");
uploadData.Upload = upload;
uploadData.FileStream = fileStream;
uploadData.FooterBytes = footerBytes;
uploadData.HeaderBytes = headerBytes;
uploadData.BytesWritten = 0;
m_uploadData = uploadData;
m_request = (HttpWebRequest)WebRequest.Create(uri);
m_request.Method = "POST";
m_request.AllowWriteStreamBuffering = false;
m_request.ContentType = string.Format(contentType, boundarystr);
m_request.ContentLength = fileStream.Length + headerBytes.Length + footerBytes.Length;
var asyncResult = m_request.BeginGetRequestStream((ar) => { GetRequestStreamCallback(ar, uploadData); }, m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Start upload failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult, UploadData uploadData)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
Stream postStream = request.EndGetRequestStream(asynchronousResult);
postStream.Write(uploadData.HeaderBytes, 0, uploadData.HeaderBytes.Length);
var args = new UploadEventArgs();
args.Upload = uploadData.Upload;
args.Progress = 1;
OnProgressChanged(args);
uploadData.PostStream = postStream;
WriteNextChunck(uploadData);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Header write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
m_uploadData.FileStream.Close();
m_uploadData.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void WriteNextChunck(UploadData upload)
{
try
{
if ((upload.FileStream.Length - upload.BytesWritten) >= 16 * 1024)
{
upload.Buffer = new byte[16 * 1024];
}
else
{
// Last part
upload.Buffer = new byte[upload.FileStream.Length - upload.BytesWritten];
}
upload.FileStream.Read(upload.Buffer, 0, (int)upload.Buffer.Length);
upload.PostStream.BeginWrite(upload.Buffer, 0, upload.Buffer.Length, BeginWriteCallback, upload);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Buffer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
upload.FileStream.Close();
upload.PostStream.Close();
OnUploadComplete(argsStopped);
}
}
private void BeginWriteCallback(IAsyncResult ar)
{
try
{
var upload = ar.AsyncState as UploadData;
upload.PostStream.EndWrite(ar);
upload.BytesWritten += upload.Buffer.Length;
var args = new UploadEventArgs();
args.Upload = upload.Upload;
args.Progress = (int)(((decimal)upload.BytesWritten / (decimal)upload.FileStream.Length) * 100);
OnProgressChanged(args);
if (m_isStopped)
{
upload.FileStream.Close();
upload.PostStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload stopped");
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
return;
}
// write next chunck
if (upload.BytesWritten < upload.FileStream.Length)
{
WriteNextChunck(upload);
}
if (upload.BytesWritten >= upload.FileStream.Length)
{
WriteFooter(upload);
}
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Upload write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void WriteFooter(UploadData upload)
{
try
{
upload.PostStream.Write(upload.FooterBytes, 0, upload.FooterBytes.Length);
upload.PostStream.Close();
var asyncResult = m_request.BeginGetResponse(new AsyncCallback(GetResponseCallback), m_request);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = new Exception("Footer write failed: " + ex.Message);
var argsStopped = new UploadEventArgs();
argsStopped.Upload = m_uploadData.Upload;
OnUploadComplete(argsStopped);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
streamResponse.Close();
streamRead.Close();
response.Close();
m_uploadData.FileStream.Close();
m_uploadData.Upload.UploadInfo.StatusCode = response.StatusCode;
if (response.StatusCode == HttpStatusCode.NoContent)
{
m_uploadData.Upload.UploadInfo.Exception = null;
}
else
{
m_uploadData.Upload.UploadInfo.Exception = new Exception(responseString);
}
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
args.Progress = 100;
OnUploadComplete(args);
}
catch (Exception ex)
{
m_uploadData.Upload.UploadInfo.StatusCode = HttpStatusCode.NotFound;
m_uploadData.Upload.UploadInfo.Exception = ex;
var args = new UploadEventArgs();
args.Upload = m_uploadData.Upload;
OnUploadComplete(args);
}
}
private string GetParamsString(Dictionary<string, string> parameters)
{
bool needsCLRF = false;
string result = "";
foreach (var param in parameters)
{
// Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
// Skip it on the first parameter, add it to subsequent parameters.
if (needsCLRF)
result += "\r\n";
needsCLRF = true;
string prm = string.Format("--{0}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Disposition: form-data; name={1}\r\n\r\n{2}",
boundarystr,
param.Key,
param.Value);
result += prm;
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundarystr + "\r\n";
result += footer;
return result;
}
protected virtual void OnUploadComplete(UploadEventArgs e)
{
if (UploadCompleted != null)
UploadCompleted(this, e);
}
protected virtual void OnProgressChanged(UploadEventArgs e)
{
if (ProgressChanged != null)
ProgressChanged(this, e);
}
public void Stop()
{
m_isStopped = true;
}
}
}
I am using this encryption class in a J2ME app. My J2ME application works fine on all Nokia devices. The app doesn't work on the Chinese MIw200 phone. Perhaps this cryptography is not supported on that phone? Is there another solution or any other method to encrypt and decrypt?
Please help me. Thanks a lot in advance.
My code is below:
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class AESEncoder {
private SecretKeySpec keyspec;
private Cipher cipher;
private String secretkey;
public AESEncoder(String secretkey) {
this.secretkey = secretkey;
keyspec = new SecretKeySpec(secretkey.getBytes(), 0, 16, "AES");
// keyspec=new SecretKeySpec(key, offset, len, secretkey);
try {
cipher = Cipher.getInstance("AES/ECB/NoPadding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception {
if (text == null || text.length() == 0) {
throw new Exception("Empty string");
}
int encrypted = 0;
byte[] bytenc = null;//new byte[32];
byte[] input = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
// byte empty[]=padString(text).getBytes();
// encrypted = cipher.doFinal(padString(text).getBytes());
// encrypted=cipher.doFinal(padString(text).getBytes(), 0, 0, padString(text).getBytes(), 0);
input = padString(text).getBytes();
bytenc = new byte[input.length];
encrypted = cipher.doFinal(input, 0, input.length, bytenc, 0);
String str = new String(bytenc, 0, encrypted);
// encrypted=cipher.update(padString(text).getBytes(), 0, 0, 0, 0);
// System.out.println("Encrypted is:>>" + str);
// bytenc=hexToBytes(String.valueOf(encrypted));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return bytenc;
}
public String encrypt_hsm(String text) throws Exception {
if (text == null || text.length() == 0) {
throw new Exception("Empty string");
}
String base64=null;
int encrypted = 0;
byte[] bytenc = null;//new byte[32];
byte[] input = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec);
// byte empty[]=padString(text).getBytes();
// encrypted = cipher.doFinal(padString(text).getBytes());
// encrypted=cipher.doFinal(padString(text).getBytes(), 0, 0, padString(text).getBytes(), 0);
input = padString(text).getBytes();
bytenc = new byte[input.length];
encrypted = cipher.doFinal(input, 0, input.length, bytenc, 0);
String str = new String(bytenc, 0, encrypted);
base64 = Base64.encode(bytenc);
// encrypted=cipher.update(padString(text).getBytes(), 0, 0, 0, 0);
// System.out.println("Encrypted is:>>" + str);
// bytenc=hexToBytes(String.valueOf(encrypted));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return base64;
}
public byte[] decrypt(String code) throws Exception {
if (code == null || code.length() == 0) {
throw new Exception("Empty string");
}
int decrypted = 0;
byte[] bytedec = null;
byte[] input = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec);
// input=hexToBytes(code);
input = Base64ToBytes(code);
bytedec = new byte[input.length];
decrypted = cipher.doFinal(input, 0, input.length, bytedec, 0);
String str = new String(bytedec, 0, decrypted);
// System.out.println("Decrypted is:>>" + str);
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return bytedec;
}
public static String bytesToHex(byte[] bsData) {
int nDataLen = bsData.length;
String sHex = "";
for (int nIter = 0; nIter < nDataLen; nIter++) {
int nValue = (bsData[nIter] + 256) % 256;
int nIndex1 = nValue >> 4;
sHex += Integer.toHexString(nIndex1);
int nIndex2 = nValue & 0x0f;
sHex += Integer.toHexString(nIndex2);
}
return sHex;
}
public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}
private static String padString(String source) {
char paddingChar = ' ';
int size = 32;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
// System.out.println("====>Pad String:" + source);
return source;
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private byte[] Base64ToBytes(String code) {
code = code.replace('-', '+');
code = code.replace('_', '/');
code = code.replace(',', '=');
System.out.println("Final Base 64:"+code);
byte[] aesString = Base64.decode(code);
// System.out.println("Base64 after decoding:"+new String(aesString));
return aesString;
}
}
Please post a stack trace. Otherwise we are all just guessing.
AES is a required cipher, sometime between v4 and v7. Spend some time and confirm that this cipher isn't available on the MIw200.
Someone getting "AES not available" on a Mac got some suggestions.
Try allowing the system to fall back to 3DES or DES, instead of forcing AES. Here's an example that tests encryption with each algorithm.
Try using the BouncyCastle API. Here is a how-to guide.
I want to force my program to wait some moments after doing something, and then do somwthing else, in asp.net and silverlight.
(In Detail, I want to upload an image by silverlight program, and then show it in my page by an Image control. But when I upload images which their size is about 6KB or upper, the image doesn't show, however it has been uplaoded successfully. I think that waiting some moments may solve the problem)
May anyone guide me?
thank you
I use the code in this page
This is the code in MyPage.Xaml:
private void UploadBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = UPLOAD_DIALOG_FILTER;
if ((bool)dlg.ShowDialog())
{
progressBar.Visibility = Visibility.Visible;
progressBar.Value = 0;
_fileName = dlg.File.Name;
UploadFile(_fileName, dlg.File.OpenRead());
}
else
{
//user clicked cancel
}
}
private void UploadFile(string fileName, Stream data)
{
// Just kept here
progressBar.Maximum = data.Length;
UriBuilder ub = new UriBuilder("http://mysite.com/receiver.ashx");
ub.Query = string.Format("fileName={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
try
{
c.OpenWriteAsync(ub.Uri);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[input.Length];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, buffer.Length);
}
progressBar.Value += input.Length;
if (progressBar.Value >= progressBar.Maximum)
{
progressBar.Visibility = System.Windows.Visibility.Collapsed;
loadImage();
}
}
private void loadImage()
{
Uri ur = new Uri("http://mysite.com/upload/" + _fileName);
img1.Source = new BitmapImage(ur);
}
And this is receiver.ashx:
public void ProcessRequest(HttpContext context)
{
string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/upload/" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[stream.Length];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
URL: http://monSite/GET.asp
we must authenticate before getting the result.
I want to send the login and password with HttpConn.setRequestMethod (HttpConnection.POST) and retrieve the XML file with HttpConn.setRequestMethod (HttpConnection.GET) with the same HTTP Client.
conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);
postData.append("userName",_username);
postData.append("passWord", _password);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());
byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();
os.write(postBytes);
os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;
InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");
while ((len = isr.read(buffer, 0, size)) > 0)
{
buff.append(buffer, 0, len);
total += len;
}
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the HttpConnection.POST works very well but GET no (login failed: the authentication parameter does not saved)
In HttpConnection.GET request you need to append attribute in your url like:
String url="http://www.xyz?userName="+_username+"&password="+_password+"";
and then get the InputStream
below link may be helpful for you
http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075