HTTP delete request in J2ME - http

I'm trying to send an delete request on a Rails Server from J2ME
The output is
STATUS: 422
and the element is not deleted.
Here's the code:
HttpConnection hc = null;
InputStream istrm = null;
String msg = "_method=DELETE";
System.out.println(id);
try {
hc = (HttpConnection) Connector.open(server + "documents/" + id + ".xml");
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
hc.setRequestProperty("Content-length", "" + msg.getBytes().length);
OutputStream out = hc.openOutputStream();
out.write(msg.getBytes());
out.close();
System.out.println("STATUS: " + hc.getResponseCode()+ hc.getResponseMessage());

Add the following statements before closing outputstream
int res_code=hc.getResponseCode();
if(res_code==HttpConnection.HTTP_OK)
{
//Success
}
else
{
//Failure
}
.........
//After performing all operations then close streams and connection
out.close();
hc.close();
Try it.All the best

Related

Recieve/Accept file in WEBDAV from httpwebrequest POST or PUT in asp.net

Suppose I have sample Upload file method like this in POStFile.aspx.
This method POST file (upload file) to http WEBDAV url.
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) {
log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) {
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try {
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
} catch(Exception ex) {
log.Error("Error uploading file", ex);
if(wresp != null) {
wresp.Close();
wresp = null;
}
} finally {
wr = null;
}
}
From here
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
HttpUploadFile("http://your.server.com/upload",
#"C:\test\test.jpg", "file", "image/jpeg", nvc);
Question 1 : Shouldn't the url should be like "http://your.server.com/upload.aspx" instead of "http://your.server.com/upload"
If I give url like "http://your.server.com/upload" then i get 405 error method not found.
So it should point to any page.
Question 2 : How should I receive the post and save the file in upload.aspx.
Can the file directly uploaded to remote server without any receiving
page ?
This question was about "File transfer to WEBDAV http URL using or POST or PUT method"
Above is sample POST method.Similarly there can by PUT method which is little different from POST method.
Question 1 : Shouldn't the url should be like "http://your.server.com/upload.aspx" instead of "http://your.server.com/upload"
For novice man like me, main confusion is URL.It entirely depend upon "How WEBDAV server want to receive POST or PUT method ?"
I think for POST method ,there should be one receiving page which accept file and other parameters from POSTfile page and save the file to disk.
I don't know about .net code but WEB API has inbuilt feature which can parse data like "multipart/form-data; boundary=---------------------------8d60ff73d4553cc"
Below code is just sample code,
[HttpPost]
public async Task<FileUploadDetails> Post()
{
// file path
var fileuploadPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
////
var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);
// Read the MIME multipart asynchronously
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
string uploadingFileName = multiFormDataStreamProvider
.FileData.Select(x => x.LocalFileName).FirstOrDefault();
// Files
//
foreach (MultipartFileData file in multiFormDataStreamProvider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}
// Form data
//
foreach (var key in multiFormDataStreamProvider.FormData.AllKeys)
{
foreach (var val in multiFormDataStreamProvider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}
//Create response
return new FileUploadDetails
{
FilePath = uploadingFileName,
FileName = Path.GetFileName(uploadingFileName),
FileLength = new FileInfo(uploadingFileName).Length,
FileCreatedTime = DateTime.Now.ToLongDateString()
};
return null;
}
So url in POSTFile.aspx page should point to API method in this case,
"http://your.server.com/api/fileUpload"
where fileUpload is api controller name.
If you are using HTTP PUT method then
i) you want to receive it in pro grammatically handle it.Write PUT method similar to POST method in api class.
ii) you want to directly save the file to folder using PUT method.
so URL in this case can be,
"http://your.server.com/Imagefolder"
Yes this can be done with extra IIS setting.
Create virtual directory in Target folder,beside few other thing.

J2ME App in Blackberry Network connectivity issue

I have developed a J2ME App which i tried in Blackberry device. Application launched successfully but when i am making a network call its throwing exception. Currently the Blackberry device which i own doesn't have BIS(Blackberry Internet Service) plan enabled. I am testing it in Blackberry OS version less than six.
Here is my Coding for HTTP Get Method
public static Vector httpGet(String uri, String param) {
Vector buf = new Vector();
try {
String parameter = param;
String url = uri + "?" + parameter;
System.out.println("Passed URL:" + uri + "?" + parameter);
HttpConnection hc = (HttpConnection) Connector.open(url);
hc.setRequestMethod(HttpConnection.GET);
Commons.print(hc.getResponseCode() + ":" + HttpConnection.HTTP_OK
+ ":" + hc.getResponseMessage());
if (hc.getResponseCode() >= 400) {
hc = null;
return null;
}
InputStream inn = hc.openInputStream();
if (inn == null)
return null;
DataInputStream in = new DataInputStream(inn);
String st = "";
while ((st = readLine(in)) != null) {
buf.addElement(st);
}
if (in != null) {
in.close();
}
if (hc != null) {
hc.close();
setStatus(DataMembers.okStatus);
}
} catch (Exception ex) {
System.out.println("Error:" + ex.toString());
setStatus(DataMembers.failStatus);
buf = null;
}
return buf;
}
Does Blackberry requires BIS connection for making a network call? I am not appending any manual connection String to my URL.

Quickbooks Http Web Request code gives 400 Server error

I am using Quickbooks V3 SDK.It was also giving 400 error as In October 2014 they had changed their link from https://quickbooks.api.intuit.com/ to sandbox.quickbooks.api.intuit.com/, after correcting I can fetch results and can perform crud operations using its mentioned classes.
ServiceContext serviceContext = getServiceContext(profile);
serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/";
QueryService<Item> ItemQueryService = new QueryService<Item>(serviceContext);
return ItemQueryService.Select(c => c).ToList();
This code works perfectly.
But when i try to perform the same operation as JSON request with HTTP web request, it gives me 400 error.
I am pasting HTTP Web request code below.
HttpContext.Current.Session["serviceEndPoint"] = "https://qb.sbfinance.intuit.com/v3/company/" + profile.RealmId +"/item&query=select * from item"; //
OAuthConsumerContext consumerContext = OAuthCR();
OAuthSession oSession = OAuthSession(consumerContext);
oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
oSession.AccessToken = new TokenBase
{
Token = profile.OAuthAccessToken,
ConsumerKey = "qyprdB0F3beIfmSTdvpLG5J46xPGm2",
TokenSecret = profile.OAuthAccessTokenSecret
};
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post();
conReq.AcceptsType = "application/json";
conReq = conReq.ForUrl(HttpContext.Current.Session["serviceEndPoint"].ToString());
string header = conReq.Context.GenerateSignatureBase();
try
{
string res = conReq.ReadBody();
}
catch (WebException we)
{
HttpWebResponse rsp = (HttpWebResponse)we.Response;
if (rsp != null)
{
try
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string res2 = rsp.StatusCode + " | " + reader.ReadToEnd();
}
}
catch (Exception)
{
string res = "Status code: " + rsp.StatusCode;
}
}
else
{
string res = "Error Communicating with Mock Service" + we.Message;
}
}
}
They have mentioned wrong url on their sdk which is https://qb.sbfinance.intuit.com/v3/company/xxxxxxxxx/
but correct one is
https://sandbox-quickbooks.api.intuit.com/v3/company/xxxxxxxxxx/

EndGetResponse can only be called once for each asynchronous operation?

Trying to implement a WebRequest and return to the caller synchronously.
I have tried various implementations and I think this would be the most appropriate so far.
Unfortunately the following code throws an InvalidOperationException with the message
EndGetResponse can only be called once for each asynchronous operation
I really struggled enough to make this happen and its really vital to the library I build to use the WebRequest like this.
The following code is intend to use in Windows Phone 8 and Windows 8 platforms.
I already understand the async/await pattern and used it, but it is REALLY vital for me to use the synchronous version of the web service request in a part of my library.
The code:
public void ExecuteRequest(string url, string requestData)
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Header-Key"] = "AKey";
DTOWebRequest webRequestState = new DTOWebRequest
{
Data = requestData,
Request = request
};
ManualResetEventSlim resetEventSlim = new ManualResetEventSlim(false);
// Begin the request using a delegate
request.BeginGetRequestStream(ar =>
{
DTOWebRequest requestDataObj = (DTOWebRequest )ar.AsyncState;
HttpWebRequest requestStream = (HttpWebRequest)requestDataObj.Request;
string data = requestDataObj.Data;
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(data);
try
{
// End the operation
using (Stream endGetRequestStream = requestStream.EndGetRequestStream(ar))
{
// Write to the request stream.
endGetRequestStream.Write(postBytes, 0, postBytes.Length);
}
// Get the response using a delegate
requestStream.BeginGetResponse(result =>
{
DTOWebRequest requestDataObjResult = (DTOWebRequest )ar.AsyncState;
HttpWebRequest requestResult = (HttpWebRequest)requestDataObjResult.Request;
try
{
// End the operation
using (HttpWebResponse response = (HttpWebResponse)requestResult.EndGetResponse(ar)) // Here the exception is thrown.
{
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
// The Response
string responseString = streamRead.ReadToEnd();
if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
{
FileRepository fileRepo = new FileRepository();
fileRepo.Delete(requestDataObjResult.FileName);
}
Debug.WriteLine("Response : {0}", responseString);
}
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
resetEventSlim.Set(); // Signal to return handler
}, requestDataObj);
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}, webRequestState);
resetEventSlim.Wait(5000); // Wait either for Set() or a timeout 5 secs.
}
}
Thank you.
You can't do synchronous web calls in Windows Phone and that's why you aren't.
If you were, you'd be calling GetRequestStream instead of BeginGetRequestStram/EndGetRequestStream.
The only reason to be synchronous on Windows Phone is to block the UI which is a very bad idea.
You should use an HttpClient and àsync-await` instead.
But if you really think you should (and can) do asynchronous calls on Windows Phone, you can always try something like this:
public void ExecuteRequest(string url, string requestData)
{
try
{
WebRequest request = WebRequest.Create(new Uri(url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["Header-Key"] = "AKey";
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(requestData);
using (var requestStream = request.EndGetRequestStream(request.BeginGetRequestStream(null, null)))
{
// Write to the request stream.
endGetRequestStream.Write(postBytes, 0, postBytes.Length);
}
using (var response = request.EndGetResponse(request.BeginGetResponse(null, null)))
{
using (var streamRead = new StreamReader(response.GetResponseStream()))
{
// The Response
string responseString = streamRead.ReadToEnd();
if (!string.IsNullOrWhiteSpace(requestDataObjResult.FileName))
{
var fileRepo = new FileRepository();
fileRepo.Delete(request.FileName);
}
Debug.WriteLine("Response : {0}", responseString);
}
}
}
catch (WebException webEx)
{
WebExceptionStatus status = webEx.Status;
WebResponse responseEx = webEx.Response;
Debug.WriteLine(webEx.ToString());
}
}
But I really think you should revise your decision/need.

Opening a http connection on a specific port on Blackberry

I know that you can open a connection to a URL when programming in Blackberry but is it possible to open a connection on a specific port ? For example I want to send some data to the echo port of the server to check if it is alive and measure the ping time. Any ideas ?
Try something like this;
// Create ConnectionFactory
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection descriptor
ConnectionDescriptor conDescriptor = factory.getConnection("socket://www.abc.com:portnumber");
You can specify the port number when specifying the url to open the connection.
try this code :-
String host = "Your address" ;
new Thread()
{
run()
{
try {
SocketConnection connection = (SocketConnection)Connector.open("socket://" + host + ":80");
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
// Standard HTTP GET request all in text
// Only the required Host header, no body
String request = "GET / HTTP/1.1\r\n" +
"Host:" + host + "\r\n" +
"\r\n" +
"\r\n";
out.write(request.getBytes());
out.flush();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int firstByte = in.read();
if (firstByte >= 0) {
baos.write((byte)firstByte);
int bytesAvailable = in.available();
while(bytesAvailable > 0) {
byte[] buffer = new byte[bytesAvailable];
in.read(buffer);
baos.write(buffer);
bytesAvailable = in.available();
}
}
baos.close();
connection.close();
final_OP(new String(baos.toByteArray()) );
} catch (IOException ex) {
final_OP(ex.getMessage());
}
}
}.start();
public void final_OP(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Output" + message);
}
});
}

Resources