I am working on jersey restful webservices(Java).
I want to upload or send a file to server using restful webservices.
Please help me out on this?
First of all you have to explore such terms as HTTP query structure, Multipart MIME type etc.
The simplest code with jersey would look like snippet below. It's written in scala, but you should easily get the sense:
#Path("/upload")
class UploadFileResource {
#POST
#Path("/file")
#Consumes(Array(MediaType.MULTIPART_FORM_DATA))
#Produces(Array(MediaType.TEXT_PLAIN))
def processUpload(
#FormDataParam("file") uploadedInputStream: InputStream,
#HeaderParam("Content-Length") length: Int) = {
println("Content-Length: " + length)
}
#GET
#Path("/form")
#Produces(Array(MediaType.TEXT_HTML))
def getFormMurkup() = {
"<html><body><form method='post' action='file' enctype='multipart/form-data'>" +
"<input type='file' name='file' />" +
"<input type='submit' value='Upload' />" +
"</form>" +
"</html></body>"
}
}
Related
I want to change url of host web from provider hosted app.
Basically, after completion of some business logic in my provider hosted app, I want to navigate to another page of SharePoint portal (for example the search-center page).
When I do "response.redirect" or "window.location.href" it is loading within the App iframe. I want to load the same page in main window.
Please suggest.
Updating with my logic
I have a generic method to get List home page url
public string ListHomePage(ClientContext clientContext, string listName)
{
Web spWeb = clientContext.Web;
clientContext.Load(spWeb, web => web.Url);
clientContext.ExecuteQuery();
return TokenHelper.GetAppContextTokenRequestUrl(spWeb.Url, HttpContext.Current.Server.UrlEncode(spWeb.Url + "/Lists/" + listName));
}
and I am calling following code in App page.
Response.Redirect(ListHomePage(clientContext1, "Test ListName"));
The same can be achieved using below code as the AppPart loads inside a iframe
string redirectUrl = ListHomePage(clientContext1, "Test ListName");
string script = "<script type='text/javascript'>window.parent.location.href = '" + redirectUrl + "'; </script>";
//Here I am using Telerik ScriptManager to execute script
RadScriptManager.RegisterStartupScript(this, this.GetType(), "Load", script, false);
I am currently developing a web app which should do restful service calls to existing web service api.
What I have is the base URL and the API names.
Any help on how do I start working on it?
I suppose I need to use httpbuilder for the base url I have, then followed by /api name. But how do I test it on grails if its working?
When I paste the base url on the browser it does return some xml information, so what I need is to do it on grails instead.
XML response when I paste the url through browser
<ns1:createNewUserResponse>
<userId>21</userId>
</ns1:createNewUserResponse>
So I need to be able to get this response through my web-app (grails) instead of pasting it on the browser.
EDIT*
this is a good example I found useful
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
but i do not understand the query part and how do I alter it to my need?
the URL I have contains credential of username and password, the response should return a securityToken which I need to get it out from the results. Any help would be greatly appreciated!
You can start with groovy-wslite, it provides both SOAP and REST webservice clients.
To make a call to a resfull service look at Groovy HttpBuidler - http://groovy.codehaus.org/HTTP+Builder
I have deployed a simple hello service in jboss server. I can view the wsdl file. Can someone help me with the client side. I mean how to access this service? Is there any way to access from web browser? Method deployed is
#WebMethod
public String greet( #WebParam(name = "name")
String name )
{
return "Hello" + name;
}
Try to know what is the wsdl url to access the service which you have just exposed. It might most probably be something like "http://localhost: < port-number >/ems-ejb/?wsdl"
If you type the same in the browser, you should be able to see the wsdl file (page with full of xml tags).
Once done, follow the steps provided here
Example on how to call the method once client stub is generated
String endpoint = "your wsdl url";
GreetImplServiceLocator objGreetImplServiceLocator = new GreetImplServiceLocator();
java.net.URL url = new java.net.URL(endpoint);
GreetIntf objGreetIntf = objGreetImplServiceLocator.getFaultImplPort(url);
String greetings=objFaultIntf.greet("stackoverflow");
I'm trying to do something in a console app for a test (based on some code in an HttpHandler in a web app).
Given something like this below which works for my HttpHandler which has HttpContext passed to it:
context.Response.AppendHeader("Content-Length", docContent.Length.ToString());
context.Response.AppendHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
context.Response.ContentType = MIMEType.MimeType(fileType);
context.Response.OutputStream.Write(docContent, 0, docContent.Length);
context.Response.OutputStream.Flush();
I have part of it, I think and then I get stuck:
WebClient client = new WebClient ();
client.Headers.Add("Content-Length", docContent.Length.ToString());
client.Headers.Add("content-disposition", "attachment; filename=\"" + fileName + "\"");
string ContentType = MIMEType.MimeType(fileType);
// ??
// how to build the response as an output stream from my byte array which has the data ?
MemoryStream(byte[]) can create a Stream from a byte[].
But a problem is WebClient is designed to issue HTTP requests only. If your goal is to test the server by downloading an attachment, then you'll need different headers.
If indeed you're trying to download a file, then try using WebClient.DownloadFile
On a remote client, I'm trying to create a new list in a sharepoint site. Right now, I'm building a CAML string and sending it via http post to my sharepoint site. I've used this method to update list items and create dws folders, but I can't seem to get AddList to work. I get an error "Remove server returned error:NotFound."
here is my CAML:
string soapEnv =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<AddList xmlns=\"http://schemas.microsoft.com/sharepoint/soap\">" +
"<listName>" + listName + "</listName>" +
"<description>" + "A Test list" + "</description>" +
"<templateID>100</templateID>" +
"</AddList>" +
"</soap:Body>" +
"</soap:Envelope>";
return soapEnv;
I send this in an http Post with these settings:
uri = "[my sharepoint site]/_vti_bin/lists.asmx";
WebClient client = new WebClient();
client.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/";
client.Headers["content-type"] = "text/xml; charset=utf-8";
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(uri, UriKind.Absolute), "POST", CAML);
}
catch (Exception ex)
{
MessageBox.Show("Error in upload string async: " + ex.Message);
}
Any ideas? I'm pretty certain it's not an authentication issue since I've used the exact same method in this same program to do the previously mentioned functions. The sharepoint site I'm adding the list to is a test site in which I have full read/write capabilities.
D'oh!
In this part of the soap:Envelope tag: "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance"
I had XMLSchema-instance" instead of XMLSchema\"". I needed that extra parentheses to finish that string...