Resumable Upload using Google Mail APIs throwing exception: "Bad Request" - c#-4.0

I am trying to insert mail to Google Mailbox using GMail APIs.
I want to upload mails of size more than 5 mb. So that I am using Resumable upload request.
I have used POST request first to initiate a resumable upload which gives "200 OK" response.
Post Request:
String postUrl = "https://www.googleapis.com/upload/gmail/v1/users/" + "<username>" + "/messages/send?uploadType=resumable";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest.Headers["Authorization"] = "Bearer " + f_token;// AccessToken;
httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
httpRequest.Headers["X-Upload-Content-Length"] = f_bytes.Length.ToString();
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
var response = (HttpWebResponse)httpRequest.GetResponse(); // 200 OK
From that response I get location URL to upload EML.
Location: https://www.googleapis.com/upload/gmail/v1/users//messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw
To upload EML file I used Location URL as PUT URL to create request.
putUrl = https://www.googleapis.com/upload/gmail/v1/users/<username>/messages/send?uploadType=resumable&upload_id=AEnB2UqeNYKVyyQdL07RZcbenWOqY8a2NFVIsQrbA-S-vxwUXC_W4ORQtpPx1HG6tc4Indx8AvqDjwXII3F6OW0G3wsdUMUjHw";
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = f_bytes.Length;
int EndOffset = f_bytes.Length;//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + 0 + "-" + EndOffset + "/" + f_bytes.Length;
httpRequest1.ContentType = "message/rfc822";
MemoryStream stream = new MemoryStream(f_bytes);
System.IO.Stream requestStream = httpRequest1.GetRequestStream();
{
stream.CopyTo(requestStream);
requestStream.Flush();
requestStream.Close();
}
HttpWebResponse f_webResponse = (HttpWebResponse)httpRequest1.GetResponse(); //Exception
Exception :
The remote server returned an error: (400) Bad Request.
Please suggest soluion to upload eml file in a particular folder of mailbox .

I am able to send mail using resumable upload.
if (f_MailService == null)
{
bool isCreated = createMailService(ref f_MailService);
}
FileStream fs = new FileStream(#p_EMLPath, FileMode.Open,FileAccess.Read);
Create HTTPRequest for sending mail :
string postUrl = "https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable";
HttpWebRequest f_httpRequest = (HttpWebRequest)WebRequest.Create(postUrl);
f_httpRequest.Headers["X-Upload-Content-Type"] = "message/rfc822";
f_httpRequest.Headers["X-Upload-Content-Length"] = fs.Length.ToString();
f_httpRequest.Headers["Authorization"] = "Bearer " + f_token;
f_httpRequest.Method = "POST";
//f_httpRequest.ContentLength = 524288;
f_httpRequest.ContentType = "application/json; charset=UTF-8";//"message/rfc822";
f_httpRequest.ContentLength = fs.Length;
f_httpRequest.Timeout = 6000000;
f_httpRequest.SendChunked = true;
Get Response for first POST request :
try
{
using (Stream f_ObjHttpStream = f_httpRequest.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
try
{
using (var response = (HttpWebResponse)f_httpRequest.GetResponse())
{
// data = ReadResponse(response);
UploadUrl = response.Headers["Location"].ToString();
}
}
catch (WebException exception)
{
using (var response = (HttpWebResponse)exception.Response)
{
// data = ReadResponse(response);
}
}
Read EML File & send chunk data to upload
byte[] Arrbyte = new byte[1024];
int ReadByte = 0;
while (fs.Length > ReadByte)
{
bool ac = false;
int ByteRead = 0;
byte[] Data = new byte[4194304];
byte[] LastData;
//Read block of bytes from stream into the byte array
// if (ReadByte == 0)
{
ByteRead = fs.Read(Data, 0, Data.Length);
}
//else
{
if ((ReadByte + Data.Length) > fs.Length)
{
//fs.Length - ReadByte-
LastData = new byte[fs.Length - ReadByte];
ByteRead = fs.Read(LastData, 0, LastData.Length);
CallPUTReq(fs.Length, LastData);
ac = true;
}
}
//f_MsgRawStr = Convert.ToBase64String(f_bytes).TrimEnd(padding).Replace('+', '-').Replace('/', '_');
ReadByte = ReadByte + ByteRead;
if (ac == false)
{
CallPUTReq(fs.Length, Data);
}
//long pos = fs.Seek(0, SeekOrigin.Current );
//fs.Position = ReadByte;
}
private void CallPUTReq(long p_lenth, byte[] Arrbyte)
{
try
{
String postUrl = UploadUrl; //"https://www.googleapis.com/upload/gmail/v1/users/ab#edu.cloudcodes.com/messages/send?uploadType=resumable&upload_id=AEnB2UqZNtZVwWulAOhAVoFp-pZ-vTMcIXOpt_0dH_6jJecpm2Y1MNOGkE6JoDb0kn9Dt4yuHHMZWR--dBncxWQkZctF9h6jiPSL5uJDKeYE9Ut1c7-fImc";
int EndOffset = 0;
HttpWebRequest httpRequest1 = (HttpWebRequest)WebRequest.Create(postUrl);
httpRequest1.Method = "PUT";
httpRequest1.ContentLength = Arrbyte.Length;
if (rangeStartOffset == 0)
{
EndOffset = Arrbyte.Length - 1;
}
else
{
EndOffset = rangeStartOffset + Arrbyte.Length - 1;
if (EndOffset > p_lenth)
{
EndOffset = Convert.ToInt32(p_lenth);
httpRequest1.ContentLength = EndOffset - rangeStartOffset;
}
}//5120000;5242880
httpRequest1.Headers["Content-Range"] = "bytes " + rangeStartOffset + "-" + EndOffset + "/" + p_lenth; //"bytes */" + p_lenth; //
httpRequest1.ContentType = "message/rfc822";
httpRequest1.Timeout = 6000000;
UTF8Encoding encoding = new UTF8Encoding();
Stream stream = httpRequest1.GetRequestStream();
stream.Write(Arrbyte, 0, Arrbyte.Length);
stream.Close();
try
{
using (Stream f_ObjHttpStream = httpRequest1.GetRequestStream())
{
}
}
catch (Exception EX)
{
}
WebResponse response1 = null;
try
{
using (response1 = (HttpWebResponse)httpRequest1.GetResponse())
{
}
}
catch (Exception ex)
{
// UploadUrl = response1.Headers["Location"].ToString();
}
//4194303
rangeStartOffset = EndOffset +1;
}
catch (Exception)
{
}
}

Related

Discover exact POST parameters

I'm trying to get data from a website that does not have an API documentation. I used selenium to login and navigate. Today I found the data I need, it appears after a post request.
There's any way I can get the exact post parameters to do it in my node program?
Data I need
edit 1:
the code that works from console browser scrap the data from the page and save a csv file:
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
let updateTime;
let dataStudents = "";
let anoSerie;
let turma;
let prova;
let disciplina;
class AlunoProva {
constructor(nome, Status, anoSerie, turma, prova, disciplina, modalidadeEnsino, data) {
this.nome = nome;
this.Status = Status;
this.anoSerie = anoSerie;
this.turma = turma;
this.prova = prova;
this.disciplina = disciplina;
this.modalidadeEnsino = modalidadeEnsino;
this.data = data;
}
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
blob = new Blob([data], { type: "ext/csv;charset=utf-8;" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
const atualState = "Finalizado - Digital, Não iniciado, Em progresso - Digital"
function getTurma() {
let Turma = prompt("Informe a letra da turma atual", "A");
while (Turma == null || Turma == "") {
alert("Truma inválida! Por favor, informe uma turma válida.");
Turma = prompt("Informe a letra da turma atual", "A");
}
return Turma;
}
turma = getTurma().toUpperCase();
function getCombo(id) {
let combo = document.getElementById(id);
let dataComboSelected = combo.options[combo.selectedIndex].text;
return dataComboSelected;
}
String.prototype.hashCode = function () {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
let aluno = new AlunoProva()
function dataMount(data) {
if (data !== "ESTUDANTE" && data !== "PARTICIPAÇÃO")
if (!atualState.includes(data)) {
aluno.nome = data;
dataStudents += data + ",";
}
else {
aluno.Status = data;
dataStudents += data + ",";
aluno.anoSerie = anoSerie;
dataStudents += anoSerie + ","
aluno.turma = turma;
dataStudents += turma + ","
aluno.prova = prova;
dataStudents += prova + ","
aluno.disciplina = disciplina;
dataStudents += disciplina + ","
if (anoSerie.includes("EF")) {
aluno.modalidadeEnsino = "Fundamental";
dataStudents += "Fundamental,"
}
else {
aluno.modalidadeEnsino = "Médio";
dataStudents += "Médio,"
}
aluno.data = today.toLocaleDateString();
dataStudents += today.toLocaleDateString() + "\n"
}
}
prova = getCombo('selectnn74f9d641c4DADOS.VL_FILTRO_AVALIACAO')
disciplina = getCombo('select3lw7fc885326DADOS.VL_FILTRO_DISCIPLINA')
anoSerie = getCombo('selecty0fuc3bed07cDADOS.VL_FILTRO_ETAPA')
Array.from($$("body table tr *")).forEach((el) => {
el = String(el.innerHTML)
if (el.indexOf('Atualizado') === 0) {
updateTime = el;
} else if (el.length != 0 && el != undefined) {
dataMount(el);
}
});
let hashname = (anoSerie + turma + prova + disciplina + JSON.stringify(today.toLocaleDateString())).toString();
fileName = `${anoSerie} - ${turma} - ${prova} - ${disciplina}"${hashname.hashCode()}".csv`
saveData(dataStudents, fileName);
I'm having a problem with selectors on node, just rebember that I'm not conected with the site, I'm simulating a navigation with selenium. All the frameworks I checked to help me with selectors needed that I provide an url, but I can't, the only way I found to enter the system is from selenium navigation to simulating a real user.

NAudio Mp3 decoding click and pops

I followed this NAudio Demo modified to play ShoutCast.
In my full code I have to resample the incoming audio and stream it again over the network to a network player. Since I get many "clicks and pops", I came back to the demo code and I found that these artifacts are originated after the decoding block.
If I save the incoming stream in mp3 format, it is pretty clear.
When I save the raw decoded data (without other processing than the decoder) I get many audio artifacts.
I wonder whether I am doing some error, even if my code is almost equal to the NAudio demo.
Here the function from the example as modified by me to save the raw data. It is called as a new Thread.
private void StreamMP3(object state)
{
//Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//SettingsSection section = (SettingsSection)config.GetSection("system.net/settings");
this.fullyDownloaded = false;
string url = "http://icestreaming.rai.it/5.mp3";//(string)state;
webRequest = (HttpWebRequest)WebRequest.Create(url);
int metaInt = 0; // blocksize of mp3 data
int framesize = 0;
webRequest.Headers.Clear();
webRequest.Headers.Add("GET", "/ HTTP/1.0");
// needed to receive metadata informations
webRequest.Headers.Add("Icy-MetaData", "1");
webRequest.UserAgent = "WinampMPEG/5.09";
HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.RequestCanceled)
{
ShowError(e.Message);
}
return;
}
byte[] buffer = new byte[16384 * 4]; // needs to be big enough to hold a decompressed frame
try
{
// read blocksize to find metadata block
metaInt = Convert.ToInt32(resp.GetResponseHeader("icy-metaint"));
}
catch
{
}
IMp3FrameDecompressor decompressor = null;
byteOut = createNewFile(destPath, "salva", "raw");
try
{
using (var responseStream = resp.GetResponseStream())
{
var readFullyStream = new ReadFullyStream(responseStream);
readFullyStream.metaInt = metaInt;
do
{
if (mybufferedWaveProvider != null && mybufferedWaveProvider.BufferLength - mybufferedWaveProvider.BufferedBytes < mybufferedWaveProvider.WaveFormat.AverageBytesPerSecond / 4)
{
Debug.WriteLine("Buffer getting full, taking a break");
Thread.Sleep(500);
}
else
{
Mp3Frame frame = null;
try
{
frame = Mp3Frame.LoadFromStream(readFullyStream, true);
if (metaInt > 0)
UpdateSongName(readFullyStream.SongName);
else
UpdateSongName("No Song Info in Stream...");
}
catch (EndOfStreamException)
{
this.fullyDownloaded = true;
// reached the end of the MP3 file / stream
break;
}
catch (WebException)
{
// probably we have aborted download from the GUI thread
break;
}
if (decompressor == null)
{
// don't think these details matter too much - just help ACM select the right codec
// however, the buffered provider doesn't know what sample rate it is working at
// until we have a frame
WaveFormat waveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
decompressor = new AcmMp3FrameDecompressor(waveFormat);
this.mybufferedWaveProvider = new BufferedWaveProvider(decompressor.OutputFormat);
this.mybufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(200); // allow us to get well ahead of ourselves
framesize = (decompressor.OutputFormat.Channels * decompressor.OutputFormat.SampleRate * (decompressor.OutputFormat.BitsPerSample / 8) * 20) / 1000;
//this.bufferedWaveProvider.BufferedDuration = 250;
}
int decompressed = decompressor.DecompressFrame(frame, buffer, 0);
//Debug.WriteLine(String.Format("Decompressed a frame {0}", decompressed));
mybufferedWaveProvider.AddSamples(buffer, 0, decompressed);
while (mybufferedWaveProvider.BufferedDuration.Milliseconds >= 20)
{
byte[] read = new byte[framesize];
mybufferedWaveProvider.Read(read, 0, framesize);
byteOut.Write(read, 0, framesize);
}
}
} while (playbackState != StreamingPlaybackState.Stopped);
Debug.WriteLine("Exiting");
// was doing this in a finally block, but for some reason
// we are hanging on response stream .Dispose so never get there
decompressor.Dispose();
}
}
finally
{
if (decompressor != null)
{
decompressor.Dispose();
}
}
}
OK i found the problem. I included the shoutcast metadata to the MP3Frame.
See the comment "HERE I COLLECT THE BYTES OF THE MP3 FRAME" to locate the correct point to get the MP3 frame with no streaming metadata.
The following code runs without audio artifacts:
private void SHOUTcastReceiverThread()
{
//-*- String server = "http://216.235.80.18:8285/stream";
//String serverPath = "/";
//String destPath = "C:\\temp\\"; // destination path for saved songs
HttpWebRequest request = null; // web request
HttpWebResponse response = null; // web response
int metaInt = 0; // blocksize of mp3 data
int count = 0; // byte counter
int metadataLength = 0; // length of metadata header
string metadataHeader = ""; // metadata header that contains the actual songtitle
string oldMetadataHeader = null; // previous metadata header, to compare with new header and find next song
//CircularQueueStream framestream = new CircularQueueStream(2048);
QueueStream framestream = new QueueStream();
framestream.Position = 0;
bool bNewSong = false;
byte[] buffer = new byte[512]; // receive buffer
byte[] dec_buffer = new byte[decSIZE];
Mp3Frame frame;
IMp3FrameDecompressor decompressor = null;
Stream socketStream = null; // input stream on the web request
// create web request
request = (HttpWebRequest)WebRequest.Create(server);
// clear old request header and build own header to receive ICY-metadata
request.Headers.Clear();
request.Headers.Add("GET", serverPath + " HTTP/1.0");
request.Headers.Add("Icy-MetaData", "1"); // needed to receive metadata informations
request.UserAgent = "WinampMPEG/5.09";
// execute request
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
// read blocksize to find metadata header
metaInt = Convert.ToInt32(response.GetResponseHeader("icy-metaint"));
try
{
// open stream on response
socketStream = response.GetResponseStream();
var readFullyStream = new ReadFullyStream(socketStream);
frame = null;
// rip stream in an endless loop
do
{
if (IsBufferNearlyFull)
{
Debug.WriteLine("Buffer getting full, taking a break");
Thread.Sleep(500);
frame = null;
}
else
{
int bufLen = readFullyStream.Read(buffer, 0, buffer.Length);
try
{
if (framestream.CanRead && framestream.Length > 512)
frame = Mp3Frame.LoadFromStream(framestream);
else
frame = null;
}
catch (Exception ex)
{
frame = null;
}
if (bufLen < 0)
{
Debug.WriteLine("Buffer error 1: exit.");
return;
}
// processing RAW data
for (int i = 0; i < bufLen; i++)
{
// if there is a header, the 'headerLength' would be set to a value != 0. Then we save the header to a string
if (metadataLength != 0)
{
metadataHeader += Convert.ToChar(buffer[i]);
metadataLength--;
if (metadataLength == 0) // all metadata informations were written to the 'metadataHeader' string
{
string fileName = "";
string fileNameRaw = "";
// if songtitle changes, create a new file
if (!metadataHeader.Equals(oldMetadataHeader))
{
// flush and close old byteOut stream
if (byteOut != null)
{
byteOut.Flush();
byteOut.Close();
byteOut = null;
}
if (byteOutRaw != null)
{
byteOutRaw.Flush();
byteOutRaw.Close();
byteOutRaw = null;
}
timeStart = timeEnd;
// extract songtitle from metadata header. Trim was needed, because some stations don't trim the songtitle
//fileName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';StreamUrl)").Groups[2].Value.Trim();
fileName = Regex.Match(metadataHeader, "(StreamTitle=')(.*)(';)").Groups[2].Value.Trim();
// write new songtitle to console for information
if (fileName.Length == 0)
fileName = "shoutcast_test";
fileNameRaw = fileName + "_raw";
framestream.reSetPosition();
SongChanged(this, metadataHeader);
bNewSong = true;
// create new file with the songtitle from header and set a stream on this file
timeEnd = DateTime.Now;
if (bWrite_to_file)
{
byteOut = createNewFile(destPath, fileName, "mp3");
byteOutRaw = createNewFile(destPath, fileNameRaw, "raw");
}
timediff = timeEnd - timeStart;
// save new header to 'oldMetadataHeader' string, to compare if there's a new song starting
oldMetadataHeader = metadataHeader;
}
metadataHeader = "";
}
}
else // write mp3 data to file or extract metadata headerlength
{
if (count++ < metaInt) // write bytes to filestream
{
//HERE I COLLECT THE BYTES OF THE MP3 FRAME
framestream.Write(buffer, i, 1);
}
else // get headerlength from lengthbyte and multiply by 16 to get correct headerlength
{
metadataLength = Convert.ToInt32(buffer[i]) * 16;
count = 0;
}
}
}//for
if (bNewSong)
{
decompressor = createDecompressor(frame);
bNewSong = false;
}
if (frame != null && decompressor != null)
{
framedec(decompressor, frame);
}
// fine Processing dati RAW
}//Buffer is not full
SHOUTcastStatusProcess();
} while (playbackState != StreamingPlaybackState.Stopped);
} //try
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (byteOut != null)
byteOut.Close();
if (socketStream != null)
socketStream.Close();
if (decompressor != null)
{
decompressor.Dispose();
decompressor = null;
}
if (null != request)
request.Abort();
if (null != framestream)
framestream.Dispose();
if (null != bufferedWaveProvider)
bufferedWaveProvider.ClearBuffer();
//if (null != bufferedWaveProviderOut)
// bufferedWaveProviderOut.ClearBuffer();
if (null != mono16bitFsinStream)
{
mono16bitFsinStream.Close();
mono16bitFsinStream.Dispose();
}
if (null != middleStream2)
{
middleStream2.Close();
middleStream2.Dispose();
}
if (null != resampler)
resampler.Dispose();
}
}
public class QueueStream : MemoryStream
{
long ReadPosition = 0;
long WritePosition = 0;
public QueueStream() : base() { }
public override int Read(byte[] buffer, int offset, int count)
{
Position = ReadPosition;
var temp = base.Read(buffer, offset, count);
ReadPosition = Position;
return temp;
}
public override void Write(byte[] buffer, int offset, int count)
{
Position = WritePosition;
base.Write(buffer, offset, count);
WritePosition = Position;
}
public void reSetPosition()
{
WritePosition = 0;
ReadPosition = 0;
Position = 0;
}
}
private void framedec(IMp3FrameDecompressor decompressor, Mp3Frame frame)
{
int Ndecoded_samples = 0;
byte[] dec_buffer = new byte[decSIZE];
Ndecoded_samples = decompressor.DecompressFrame(frame, dec_buffer, 0);
bufferedWaveProvider.AddSamples(dec_buffer, 0, Ndecoded_samples);
NBufferedSamples += Ndecoded_samples;
brcnt_in.incSamples(Ndecoded_samples);
if (Ndecoded_samples > decSIZE)
{
Debug.WriteLine(String.Format("Too many samples {0}", Ndecoded_samples));
}
if (byteOut != null)
byteOut.Write(frame.RawData, 0, frame.RawData.Length);
if (byteOutRaw != null) // as long as we don't have a songtitle, we don't open a new file and don't write any bytes
byteOutRaw.Write(dec_buffer, 0, Ndecoded_samples);
frame = null;
}
private IMp3FrameDecompressor createDecompressor(Mp3Frame frame)
{
IMp3FrameDecompressor dec = null;
if (frame != null)
{
// don't think these details matter too much - just help ACM select the right codec
// however, the buffered provider doesn't know what sample rate it is working at
// until we have a frame
WaveFormat srcwaveFormat = new Mp3WaveFormat(frame.SampleRate, frame.ChannelMode == ChannelMode.Mono ? 1 : 2, frame.FrameLength, frame.BitRate);
dec = new AcmMp3FrameDecompressor(srcwaveFormat);
bufferedWaveProvider = new BufferedWaveProvider(dec.OutputFormat);// decompressor.OutputFormat
bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(400); // allow us to get well ahead of ourselves
// ------------------------------------------------
//Create an intermediate format with same sampling rate, 16 bit, mono
middlewavformat = new WaveFormat(dec.OutputFormat.SampleRate, 16, 1);
outwavFormat = new WaveFormat(Fs_out, 16, 1);
// wave16ToFloat = new Wave16ToFloatProvider(provider); // I have tried with and without this converter.
wpws = new WaveProviderToWaveStream(bufferedWaveProvider);
//Check middlewavformat.Encoding == WaveFormatEncoding.Pcm;
mono16bitFsinStream = new WaveFormatConversionStream(middlewavformat, wpws);
middleStream2 = new BlockAlignReductionStream(mono16bitFsinStream);
resampler = new MediaFoundationResampler(middleStream2, outwavFormat);
}
return dec;
}

Exception on downloading pdf from envelope

When i run this code.The Content is not allowed in prolog is coming.What is wroung in my code.
Here is code.
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class GetEnvelopeDoc
{
// Enter your info:
static String username = "*****";
static String password = "*****";
static String integratorKey = "******";
static String envelopeId = "**************";
static String envelopeUri = "/envelopes/" + envelopeId;
public static void main(String[] args) throws Exception
{
String url = "https://demo.docusign.net/restapi/v2/login_information";
String baseURL = ""; // we will retrieve this
String accountId = ""; // will retrieve
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
int statusValue = conn.getResponseCode(); // side-effect of this call is to fire the request off
if( statusValue != 200 ) // 200 = OK
{
System.out.print("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// we use xPath to get the baseUrl and accountId from the XML response body
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream() ));
StringBuilder responseText = new StringBuilder(); String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
String token1 = "//*[1]/*[local-name()='baseUrl']";
String token2 = "//*[1]/*[local-name()='accountId']";
XPath xPath = XPathFactory.newInstance().newXPath();
baseURL = xPath.evaluate(token1, new InputSource(new StringReader(responseText.toString())));
accountId = xPath.evaluate(token2, new InputSource(new StringReader(responseText.toString())));
//--- display results
System.out.println("baseUrl = " + baseURL + "\naccountId = " + accountId);
//
// STEP 2 - Get Info on Envelope's Document(s)
//
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader(new DataInputStream( conn.getInputStream() ));
System.out.println(isr.toString());
br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
while ( (line = br.readLine()) != null)
response.append(line);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
//--- display results
System.out.println("\nDocument List -->");
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("documentId"))
System.out.print("documentId: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("name"))
System.out.print(", name: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("uri"))
{
docURIs[++cnt] = docNodes.item(j).getTextContent(); // store the uris for later
System.out.print(", uri: " + docURIs[cnt]);
}
}
System.out.println();
}
}
//
// STEP 3 - Download the document(s)
//
for( int i = 0; i < docURIs.length; i++)
{
// append document uri to url for each document
conn = (HttpURLConnection)new URL(baseURL + docURIs[i]).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
statusValue = conn.getResponseCode();
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Grab the document data and write to a local file
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
BufferedWriter out = new BufferedWriter(new FileWriter("document_" + i + ".pdf"));
out.write(response2.toString());
out.close();
}
System.out.println("\nDone downloading document(s)!");
}
}
Your question is not very clear, I don't know what you mean when you say "the content is not allowed in prolog", however it looks like you have some extra characters in your code. Was this part a copy-paste error? You have the > symbols in front of each of these lines.
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request

how to upload audio to server: Blackberry

I'm trying to upload an .amr file to the server. My Code as follows:
private static void uploadRecording(byte[] data) {
byte[] response=null;
String currentFile = getFileName(); //the .amr file to upload
StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
connectionStr.append(getString());
PostFile req;
try {
req = new PostFile(connectionStr.toString(),
"uploadedfile", currentFile, "audio/AMR", data );
response = req.send(data);
} catch (Exception e) {
System.out.println("====Exception: "+e.getMessage());
}
System.out.println("Server Response : "+new String(response));
}
public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send(byte[] fileBytes) throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream(); // <<< EXCEPTION HERE!!!
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
System.out.println("====Exception : "+e1.getMessage());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
}
Highlighted above is the code line which throws the exception: Not Connected.
Can somebody tell me what can be done to correct this? Thanks a lot.
Updated:
public static String getString()
{
String connectionString = null;
String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
else
{
ServiceBook sb = ServiceBook.getSB();
net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null)
{
connectionString = ";deviceside=true;ConnectionUID="+uid;
}
else
{
// the carrier network
if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the
// carrier's
// TCP network
System.out.println("No Uid");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier
// BIBS
// request
System.out.println("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="
+ carrierUid + ";ConnectionType=mds-public";
}
}
//(BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging
// the user unnecessarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be
// reachable.
else {
System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
}
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {
try {
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals(
"ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
} catch (Exception e) {
System.out.println("====Exception : "+e.toString());
}
return null;
}

How to upload image to server in j2me from mobile by multipart/form-data?

While I am uploading the mobile and application number in multipart from-data from mobile it is hitting the server and data is storing in database.Now I added captured image to it and sent to server it is showing an exception.
org.apache.commons.fileupload.FileUploadBase$UnknownSizeException: the request was rejected because its size is unknown
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:305)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest (ServletFileUpload.java:116)
at org.apache.jsp.photo_jsp._jspService(photo_jsp.java:103)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:384)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process (Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Unknown Source)
Here I am sending Mobile and application Number and captured image in bytes (imagecapturephoto1). Captured image is storing in view after taking photo.But when we are uploading it is showing exception.
try
{
System.out.println("url:" + serverUrl);
connection = (HttpConnection)Connector.open(serverUrl,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
connection.setRequestProperty("Accept", "application/octet-stream" );
writer = new DataOutputStream(connection.openDataOutputStream());
// writer =new DataOutputStream( conn.openOutputStream());
String name="applicationNumber", name1="mobileNumber",name3="photo",
mimeType="text/plain",mimeType2="image/jpeg";
String value="123456789", value1="9849765432",fileName="applicationphoto.jpeg";
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + applicationNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(applicationNumber);
writeString(NEWLINE);
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name1 + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + mobileNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(mobileNumber);
writeString(NEWLINE);
//uploading image...........
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name3
+ "\"; filename=\"" + fileName + "\"");
writeString(NEWLINE);
if (mimeType2 != null)
{
writeString("Content-Type: " + mimeType2);
writeString(NEWLINE);
}
writeString("Content-Length: " + imagecapturephoto1.length);
writeString(NEWLINE);
writeString(NEWLINE);
// write content
// SEND THE IMAGE
int index = 0;
int size = 1024;
do
{
System.out.println("write:" + index);
if((index+size)<=imagecapturephoto1.length)
{
writer.write(imagecapturephoto1, index, size);
}
index+=size;
}while(index<imagecapturephoto1.length);
writeString(NEWLINE);
writeString(PREFIX);
writeString(boundary);
writeString(PREFIX);
writeString(NEWLINE);
writer.flush();
//writer.write("-- ***** -- \r\n".getBytes());
serverResponseMessage = connection.getResponseMessage();
InputStream inputstream = connection.openInputStream();
// retrieve the response from server
int chnumber;
StringBuffer sbuffer =new StringBuffer();
while( ( chnumber= inputstream.read() ) != -1 )
{
sbuffer.append( (char)chnumber );
}
String resonsestring=sbuffer.toString();
int end=resonsestring.length();
int tempstr=resonsestring.indexOf(">");
statusResponse=resonsestring.substring(tempstr+1, end);
statusResponse="SUCCESS";
//outputStream.close();
writer.close();
connection.close();
return serverResponseMessage;
}
catch (Exception ex)
{
//statusResponse="SUCCESS";
ex.printStackTrace();
return null;
}
Please suggest me,How we have to upload image from mobile.I was struck from last 10 days.please suggest me how to solve this issue.
Thanks in advance.
-Teja.
kindly try following code segment, Please ignore lat-lon coding.
private void postImageToServer(String curURL) throws Exception
{
// Open up a http connection with the Web server for both send and receive operations
midlet.get_frmLog().append("HttpConnection Enter");
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
//httpConnection.setRequestProperty("lat","22.955804");
//httpConnection.setRequestProperty("lon","72.685876");
//httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
//httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());
/*lat = "23.0172";
lon = "72.3416";*/
if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
{
lat = LatLonFetcherThread.getLatitude();
lon = LatLonFetcherThread.getLongitude();
}
else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 ) // Added By KALPEN
{
if ( midlet.state == mREPORTER.STATE_READING )
{
double xLat,xLon;
try
{
GpsBt.instance().start();
//while (true)
{
gpsBt = GpsBt.instance();
if ( gpsBt.isConnected() )
{
location = gpsBt.getLocation();
//lat = location.utc;
//lon = location.utc;
lat = (location.latitude + location.northHemi);
lon = (location.longitude + location.eastHemi);
lat = lat.substring(0,lat.length()-1);
lon = lon.substring(0,lon.length()-1);
xLat = Double.parseDouble(lat) / (double)100.00;
xLon = Double.parseDouble(lon) / (double)100.00;
lat = xLat + "";
lon = xLon + "";
lat = lat.substring(0,7);
lon = lon.substring(0,7);
//lat = "23.0172";
//lon = "72.3416";
}
Thread.sleep(100);
}
}
catch ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
}
}
httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN
//String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
// + "\nLongitude: " + LatLonFetcherThread.getLongitude();
/*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/
//#style screenAlert
/*Alert latlonAlert = new Alert("LatLon alert" );
latlonAlert.setString(latlongStr);
mREPORTER.display.setCurrent(latlonAlert);*/
if(eventName == null || eventName.equals(""))
eventName = "default";
// all the headers are sending now and connection channel is establising
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);
midlet.get_frmLog().append("Write on server-->"+imageBytes.length);
DataOutputStream dos = httpConnection.openDataOutputStream();
dos.write(imageBytes);
midlet.threadFlag=true;
}
Above Method works fine with my code, as I am also trying to upload Image to Server.

Resources