How do I delete something from a server using POST? - java-me

I'm new to J2ME. How do I delete something from a server using the POST method? Samples would be of great help.

Use DELETE method instead
I would recommend Apache HTTPClient.
Example
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();

Related

Jira Plug-in ScriptRunner Escalation Service: Post request will continue to return cache response

I'm a beginner using ScriptRunner and Groovy.
I have a post request that returns an array of string. I thought it was working fine until I compared it with my Javascript post request response. (same endpoint with same param data)
How do I confirm I'm getting cache response? or how do I make sure I dont' get cache response? (if it is server-side cache, shouldn't I get the same response through Javascript call as well?)
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
wr.write( postData );
def statusArrayString = new StringBuffer();
def rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
def line;
while((line=rd.readLine()) !=null) {
statusArrayString.append(line);
}
According to the HTTP RFC the POST requests are not cached if you do not specifically set specific headers. And usually you don't.
But if you want to be sure, just add some dummy query string (e.g. timestamp) to the end of URL.

Download file from sharepoint rest service

When im trying to use following code to download file from sharepoint site using rest services
I was getting Remote server returned 403 forbidden - Please help
String fileurl = "exact sharepoint file url";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileurl);
NetworkCredential credential = new NetworkCredential("username", "password","domain");
//request.Credentials = credential;
//request.ContinueTimeout = 10000;
request.Credentials = credential;
request.Headers["UserAgent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.99 Safari/533.4";
request.Accept = "/";
// request.Headers["Accept"] = "/";
WebResponse resp = await request.GetResponseAsync();
To be able to download file from SharePoint Online/Office 365 using CSOM or REST the authentication has to be performed.
About SharePoint Online authentication
Since SharePoint Online (SPO) uses claims based authentication, you could consider the following options:
SharePointOnlineCredentials class as part of SharePoint Online
Client Components SDK provides credentials to access SharePoint
Online resources.
utilize a custom implementation, for example as explained in this great
article. The article contains code sample with class MsOnlineClaimsHelper class that implements claim-based authentication for SharePoint Online.
Consume SharePoint REST service using .NET
In order to consume SharePoint REST service using .NET you could consider the following approaches:
HttpClient - Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. (.NET Framework 4.5)
WebClient - provides common methods for sending data to and receiving data from a resource identified by a URI. (.NET Framework 1.1)
HttpWebRequest - provides an HTTP-specific implementation of the WebRequest class, more low-level then the previous ones (.NET Framework 1.1)
All of them allows to download a file from SharePoint Online.
Examples
Example 1. How to specify SPO credentials using SharePointOnlineCredentials class
var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Credentials = new SharePointOnlineCredentials(username, securedPassword);
//...
Example 2. How to specify SPO authentication cookies using MsOnlineClaimsHelper class:
var claimshelper = new MsOnlineClaimsHelper(webUri, userName, password);
var endpointUri = new Uri(webUri,string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/$value", fileUrl));
var request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
request.Method = "GET";
request.CookieContainer = claimshelper.CookieContainer;
//...
Key points:
SharePoint Auth cookies are passed via CookieContainer property
According to Files and folders REST API reference the following
endpoint is used to retrieve file content: <app web
url>/_api//web/getfilebyserverrelativeurl('<file url>')/$value
try this one :
using System.Net;
using (WebClient webClient = new WebClient ())
{
webClient.DownloadFile(fileurl , filename);
}
try this one. let me know it will work or not?
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(HttpContext.Current.Server.MapPath("~/Documents/" + documentFileName.Name), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = documentFileName.Name;
response;

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:
https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?
I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".
static void sendHello()
{
string contents = "john";
string url = "http://localhost:51450/hello/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = contents.Length;
request.ContentType = "application/x-www-form-urlencoded";
// SEND TO WEBSERVICE
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contents);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
How can I switch off the 'snapshot' view? What am I doing wrong?
The browser is requesting html so ServiceStack is returning the html snapshot.
There are a couple of ways to stop the snapshot view:
First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
...
Another method would be to add a query string parameter called format and set it to json or xml
string url = "http://localhost:51450/hello/?format=json";
Putting the specific format requesting is the practical way to do this
string url = "http://localhost:51450/hello/?format=json";
I suggest simply deleting this feature.
public override void Configure(Container container)
{
//...
this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
//...
}
Now all requests with the Content-Type=text/html will be ignored.

How can I download file with HTTPBuilder (HttpClient)?

I need to download and save file. I'm trying to use HTTPBuilder because it has simple API and supports cookies. I have written following code:
//create new httpBuilder and set cookies
def httpBuilder = ...
def file = ...
def inputStream = httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY)
FileUtils.copyInputStreamToFile(inputStream)
How can I check that file is correctly downloaded (not only the part of the file)?
For large files exception java.lang.OutOfMemoryError: Java heap space occurs on line def inputStream = httpBuilder.get... How can I solve it?
May be it's not best choise to download files by HTTPBuilder. What is the best way to download file with cookies support?
Have you tried HttpBuilder GET request with custom response-handling logic:
httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY) {
resp, inputStream ->
FileUtils.copyInputStreamToFile(inputStream)
}
If HttpBuilder has problems which is strange then you can always use the tried and true Apache HttpClient API which has full cookie support.
HttpGet req = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(req);
// validate response code, etc.
InputStream inputStream = response.getEntity().getContent();
You can add a localContext when executing the request to manage cookies.

Download file with url as http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id> using web request

I have a site collection in which Document Id feature is activated.
Documents are archived to this site collection from another site (in which Document Id is activated as well) and the only information I have about the moved file is the document id which is same between the source and the destination.
I need to download the file using web request, but my code gives '401 Unauthorised Exception'.
My code is as below:
string url = "http://<site collection>/_layouts/DocIdRedir.aspx?ID=<doc id>";
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "Get";
request.PreAuthenticate = true;
var credential= new NetworkCredential(username, password, domainname);
request.Credentials = credential;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
I need to give some sort of authentication, but could not figure it out.
Any help would be greatly appreciated.
Thanks and Regards
Arjabh
Try running your code inside of a
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//code goes here
});
block

Resources