Postman throwing 400 Bad request for multipart/form-data image upload with jersey 2.0 - http

REQUEST :
URL: http://localhost:8080/RESTfulExample/rest/file/upload
METHOD : POST
HEADER: Content-Type : multipart/form-data
RESPONSE :
HTTP Status 400 - Bad Request
The same code is working with html forms but in postman it's throwing 400 BAD REQUEST, I looked up on google for solution and found that boundary is missing, How to resolve it ? As I have to recieve files from multiple clients like mobile application and web clients via Jquery and rest client.
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
try {
String uploadedFileLocation = "/home/nash/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
System.out.println("File uploaded..........");
return Response.status(200).entity(output).build();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception " + e);
return null;
}
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Please follow these steps:
Add jersey-multipart dependency.
In Your Application Class (or in web.xml) enable MultipartFeature.class.
DO NOT Add Content-Type header in your postman request.
For me the above steps worked. Do let me know if that helped you or not.

Related

How does Unity receive http request?

I want to accept http request to order prefab move, so how to receive http request in unity 3D?
If you mean you want to build a web service in your Unity app.
RESTful-Unity is an easy-to-use plugin.
Define the api routing
RoutingManager routingManager = new RoutingManager();
routingManager.AddRoute(new Route(Route.Type.POST, "/path/to/call", "PrefabInvoke.Move"));
Create an Invoke to response the request
namespace RESTfulHTTPServer.src.invoker
{
public class PrefabInvoke : MonoBehaviour
{
public static Response Move(Request request)
{
Response response = new Response();
string responseData = "";
string json = request.GetPOSTData();
bool valid = true;
UnityInvoker.ExecuteOnMainThread.Enqueue (() => {
Debug.Log(json);
try
{
//TODO: Parse Json string and do somthing
response.SetHTTPStatusCode((int)HttpStatusCode.OK);
responseData = "sucess message";
}
catch (Exception ex)
{
valid = false;
string msg = "failed to deseiralised JSON";
responseData = msg;
}
});
// Wait for the main thread
while (responseData.Equals("")) {}
// Filling up the response with data
if (valid) {
// 200 - OK
response.SetContent(responseData);
response.SetHTTPStatusCode ((int)HttpStatusCode.OK);
response.SetMimeType (Response.MIME_CONTENT_TYPE_JSON);
} else {
// 406 - Not acceptable
response.SetContent("Somthing wrong");
response.SetHTTPStatusCode((int) HttpStatusCode.NotAcceptable);
response.SetMimeType(Response.MIME_CONTENT_TYPE_HTML);
}
return response;
}
}
}

InputStream closed unexpectedly while using Jersey MultiPart file upload & Server-Sent Events (SSE)

I'm using Jersey Multipart for uploading file to the server via Rest API. In the resource method, I accessed the file content via InputStream. I want to return the uploaded file size to the client with EventOutput using SSE so the client easily get the uploaded file size directly from upload resource method.
I'm using Jersey as JAX-RS implementation in java with Grizzly Http server. Here is my code:
#POST
#Path("upload")
#Produces(SseFeature.SERVER_SENT_EVENTS)
#Consumes("multipart/form-data;charset=utf-8")
public EventOutput upload(#FormDataParam("file") InputStream file,
#FormDataParam("file") FormDataContentDisposition fileDisposition) {
final EventOutput eventOutput = new EventOutput();
try {
new Thread(new Runnable() {
#Override
public void run() {
try {
int read = -1;
byte[] buffer = new byte[1024];
OutboundEvent.Builder eventBuilder
= new OutboundEvent.Builder();
OutboundEvent event = null;
long totalRead = 0, lastReadMB = 0;
while ((read = file.read(buffer)) != -1) {
totalRead += read;
if (lastReadMB != (totalRead / (1024 * 1024))) {
lastReadMB = totalRead / (1024 * 1024);
event = eventBuilder.name("uploaded").data(Long.class, totalRead).build();
eventOutput.write(event);
}
}
event = eventBuilder.name("uploaded").data(Long.class, totalRead).build();
eventOutput.write(event);
} catch (Exception e) {
throw new RuntimeException(
"Error when writing the event.", e);
} finally {
try {
eventOutput.close();
} catch (Exception ioClose) {
throw new RuntimeException(
"Error when closing the event output.", ioClose);
}
}
}
}).start();
return eventOutput;
} catch (Exception e) {
logger.error(e.toString(), e);
}
throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).
entity("something happened").build());
}
​
The problem is when my resource method return EventOutput as a response and request processing thread back to the I/O container, the InputStream closed and the processing thread can't access to the uploaded file. Here is the exception:
Exception in thread "Thread-1" java.lang.RuntimeException: Error when writing the event.
at com.WebService.ContentService$1.run(ContentService.java:192)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jvnet.mimepull.MIMEParsingException: java.io.IOException: Stream Closed
at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:115)
at org.jvnet.mimepull.DataFile.read(DataFile.java:77)
at org.jvnet.mimepull.FileData.read(FileData.java:69)
at org.jvnet.mimepull.DataHead$ReadMultiStream.fetch(DataHead.java:265)
at org.jvnet.mimepull.DataHead$ReadMultiStream.read(DataHead.java:219)
at java.io.InputStream.read(InputStream.java:101)
at com.WebService.ContentService$1.run(ContentService.java:181)
... 1 more
Caused by: java.io.IOException: Stream Closed
at java.io.RandomAccessFile.seek0(Native Method)
at java.io.RandomAccessFile.seek(RandomAccessFile.java:557)
at org.jvnet.mimepull.WeakDataFile.read(WeakDataFile.java:112)
... 7 more
​
1- What's the problem in the code? Why InputStream is closed in the middle of the file transfer?
2- Is there any alternative way to return the uploaded file size to the client in server side? (REQUIREMENT: the upload resource method must handle upload file asynchronously in different thread)

RESTeasy back-end - Restlet front-end : response entity null

I have some REST services on my server (Jetty, RESTeasy) and a GWT client.
I choosed to use Restlet-GWT module on the front end.
I made a JSE client (RESTeasy client) and my service is well called (i see SQL trace in the log of Jetty server) and i get an xml response.
Then i tried from GWT with Restlet. The web service is called (Jetty log) but i have a null response.
Web service (Back end):
#GET
#Path("/getArt/{id}")
#Produces("application/xml")
public Art getArt(#PathParam("id")int id){
Art art= artDAO.findById(id);
return art;
}
Front-end GWT :
public class Front_End implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Client client = new Client(Protocol.HTTP);
client.get("http://localhost:8080/rest/service/getArt/1", new Callback() {
#Override
public void onEvent(Request request, Response response) {
System.out.println("Reponse : " + response.getEntity().getText());
}
});
}
RESTeasy client working :
public Object test(int id){
try {
ClientRequest request = new ClientRequest("http://localhost:8080/rest/service/getArt/"+id);
request.accept("application/xml");
ClientResponse<String> response = request.get(String.class);
if (response.getStatus() == 200)
{
Unmarshaller un = jc.createUnmarshaller();
Object o = un.unmarshal(new StringReader(response.getEntity()));
return o;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Are RESTeasy and Restlet "compatible" ? Should i use Restlet in the back end instead of RESTeasy ? What am i missing ?
Thx in advance
It was a SOP issue.
My server was running on port 8080, and GWT on port 8888.
I used a proxy (put it in your /war in the client side) :
proxy.jsp
<%#page import="javax.naming.Context"%>
<%#page import="javax.naming.InitialContext"%><%#page session="false"%>
<%#page import="java.net.*,java.io.*" %>
<%
try {
String reqUrl = request.getQueryString();
URL url = new URL(reqUrl.substring(4));
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setRequestMethod(request.getMethod());
int clength = request.getContentLength();
if (clength > 0) {
con.setDoInput(true);
byte[] idata = new byte[clength];
request.getInputStream().read(idata,0,clength);
con.getOutputStream().write(idata,0,clength);
}
response.setContentType(con.getContentType());
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
out.println(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
response.setStatus(500);
}
%>
then in your class where you make the call, your url becomes :
String url ="proxy.jsp?url=" + URL.encode("http://localhost:8080/rest/service/getArt/1");
There is another way to solve it, check https://developers.google.com/web-toolkit/doc/1.6/tutorial/Xsite

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

Any ideas why on some links that I try to access using HttpWebRequest I am getting "The remote server returned an error: (304) Not Modified." in the code?
The code I'm using is from Jeff's post here (the page seems to have disappeared, see an archive copy at the Wayback Machine).
Note the concept of the code is a simple proxy server, so I'm pointing my browser at this locally running piece of code, which gets my browsers request, and then proxies it on by creating a new HttpWebRequest, as you'll see in the code. It works great for most sites/links, but for some this error comes up. You will see one key bit in the code is where it seems to copy the http header settings from the browser request to it's request out to the site, and it copies in the header attributes. Not sure if the issue is something to do with how it mimics this aspect of the request and then what happens as the result comes back?
case "If-Modified-Since":
request.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
I get the issue for example from http://en.wikipedia.org/wiki/Main_Page
PS. UPDATE HERE
Still can't work this out. Basically I can identify 1 link which has an issue, and it seems to work fine, 2nd time it gets the error, 3rd time OK, 4th time gets the error, 5th time OK etc. As if there is some state not getting cleared or something in the code. I've tried to clean up the code a bit using "using" type statements etc.
Here's the code. If anyone can spot why every 2nd time I browse to a link like http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css (starting at the 2nd time, not the first) via this proxy code I get the error I'd love to hear.
class Program
{
static void Main(string[] args)
{
Proxy p = new Proxy(8080);
Thread proxythread = new Thread(new ThreadStart(p.Start));
proxythread.Start();
Console.WriteLine("Proxy Started. Press Any Key To Stop...");
Console.ReadKey();
p.Stop();
}
}
public class Proxy
{
private HttpListener _listener;
private int _port;
public Proxy(int port)
{
int defaultport = 8080;
// Setup Thread Pool
System.Threading.ThreadPool.SetMaxThreads(50, 1000);
System.Threading.ThreadPool.SetMinThreads(50, 50);
// Sanitize Port Number
if (port < 1024 || port > 65535)
port = defaultport;
// Create HttpListener Prefix
string prefix = string.Format("http://*:{0}/", port);
_port = port;
// Create HttpListener
_listener = new HttpListener();
_listener.Prefixes.Add(prefix);
}
public void Start()
{
_listener.Start();
while (true)
{
HttpListenerContext request = null;
try
{
request = _listener.GetContext();
// Statistics (by Greg)
int availThreads = -1;
int compPortThreads = -1;
ThreadPool.GetAvailableThreads(out availThreads, out compPortThreads);
log("INFO", request.Request.Url.ToString(), "START - [" + availThreads + "]");
ThreadPool.QueueUserWorkItem(ProcessRequest, request);
}
catch (HttpListenerException ex)
{
log("ERROR", "NA", "INFO: HttpListenerException - " + ex.Message);
break;
}
catch (InvalidOperationException ex)
{
log("ERROR", "NA", "INFO: InvalidOperationException - " + ex.Message);
break;
}
}
}
public void Stop()
{
_listener.Stop();
}
private void log(string sev, string uri, string message)
{
Console.Out.WriteLine(Process.GetCurrentProcess().Id + " - " + sev + " (" + uri + "): " + message);
}
private void ProcessRequest(object _listenerContext)
{
#region local variables
HttpWebRequest psRequest; // Request to send to remote web server
HttpWebResponse psResponse; // Response from remote web server
List<byte> requestBody = new List<byte>(); // Byte array to hold the request's body
List<byte> responseBody = new List<byte>(); // Byte array to hold the response's body
byte[] buffer;
string uri = "";
#endregion
var listenerContext = (HttpListenerContext)_listenerContext;
uri = listenerContext.Request.Url.ToString().Replace(string.Format(":{0}", _port), "");
// Create Interent Request
HttpWebRequest internetRequest = (HttpWebRequest)WebRequest.Create(uri);
#region Build Request Up
internetRequest.Method = listenerContext.Request.HttpMethod;
internetRequest.ProtocolVersion = listenerContext.Request.ProtocolVersion;
internetRequest.UserAgent = listenerContext.Request.UserAgent;
foreach (string key in listenerContext.Request.Headers.AllKeys)
{
try
{
switch (key)
{
case "Proxy-Connection":
case "Connection":
internetRequest.KeepAlive = (listenerContext.Request.Headers[key].ToLower() == "keep-alive") ? true : false;
break;
case "Content-Length":
internetRequest.ContentLength = listenerContext.Request.ContentLength64;
break;
case "Content-Type":
internetRequest.ContentType = listenerContext.Request.ContentType;
break;
case "Accept":
internetRequest.Accept = listenerContext.Request.Headers[key];
break;
case "Host":
break;
case "Referer":
internetRequest.Referer = listenerContext.Request.Headers[key];
break;
case "If-Modified-Since":
internetRequest.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
default:
internetRequest.Headers.Add(key, listenerContext.Request.Headers[key]);
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Error settup up psRequest object. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
#region Copy content into request
buffer = new byte[1024];
using (Stream instream = listenerContext.Request.InputStream)
{
int incount = instream.Read(buffer, 0, buffer.Length);
while (incount > 0)
{
internetRequest.GetRequestStream().Write(buffer, 0, incount);
incount = instream.Read(buffer, 0, buffer.Length);
}
}
#endregion
// Get Internet Response
HttpWebResponse internetResponse = null;
try
{
using (internetResponse = (HttpWebResponse)internetRequest.GetResponse())
{
#region Configure Local Response Header Keys
foreach (string key in internetResponse.Headers.Keys)
{
try
{
switch (key)
{
case "Transfer-Encoding":
listenerContext.Response.SendChunked = (internetResponse.Headers[key].ToLower() == "chunked") ? true : false;
break;
case "Content-Length":
listenerContext.Response.ContentLength64 = internetResponse.ContentLength;
break;
case "Content-Type":
listenerContext.Response.ContentType = internetResponse.Headers[key];
break;
case "Keep-Alive":
listenerContext.Response.KeepAlive = true;
break;
default:
listenerContext.Response.Headers.Add(key, internetResponse.Headers[key]);
break;
}
}
catch (Exception ex)
{
log("ERROR", uri, "Error settup up listenerContext.Response objects. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
try
{
// Transfer the body data from Internet Response to Internal Response
buffer = new byte[1024];
using (Stream inputStream = internetResponse.GetResponseStream())
{
int outcount = inputStream.Read(buffer, 0, buffer.Length);
while (outcount > 0)
{
listenerContext.Response.OutputStream.Write(buffer, 0, outcount);
outcount = inputStream.Read(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
log("ERROR", uri, "Could not obtain response from URI: " + ex.Message);
}
finally
{
listenerContext.Response.OutputStream.Close();
}
}
}
catch (Exception ex)
{
//if (ex is InvalidOperationException ||
// ex is ProtocolViolationException ||
// ex is WebException)
//{
// log(uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
// listenerContext.Response.Close();
// return;
//}
//else { throw; }
log("ERROR", uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
listenerContext.Response.Close();
}
}
}
And here is an example of what I see - first hit is good, 2nd has error...
Proxy Started. Press Any Key To Stop...
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - ERROR (http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css): Could not successfully get response: System.Net.WebException - The remote server returned an error: (304) Not Modified.
First, this is not an error. The 3xx denotes a redirection. The real errors are 4xx (client error) and 5xx (server error).
If a client gets a 304 Not Modified, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.
This is intended behavior.
When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.
The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ? at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').
After timestamp it should be axios.get(/api/products?${Date.now()}.
It will resolve your 304 status code.
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
go to android studio
Tools
Android
SDK Manager
Appearance & Behavior
Android SDK

How to describe an ASP.NET Web Service ENUM for JSR-172 (Java ME) Consumption

I have .NET Web Service and I am trying to use that web service from a Java Mobile phone. I am also using the NetBeans development environment with the web service tool kit. When I try to create the proxies, it falters on the enumerations stating that the simple types are not supported. Is there a way to describe the enumeration type in the WSDL so it is understandable to the toolkit?
// send a POST request to web server
public String sendPostRequest(String urlstring, String requeststring)
{
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
String message = "";
// specifying the query string
String requeststring = "request=gettimestamp";
try
{
// openning up http connection with the web server
// for both read and write access
hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);
// setting the request method to POST
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// obtaining output stream for sending query string
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
// sending query string to web server
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// flush outdos.flush();
// obtaining input stream for receiving HTTP response
dis = new DataInputStream(hc.openInputStream());
// reading the response from web server character by character
int ch;
while ((ch = dis.read()) != -1)
{
message = message + (char) ch;
}
}
catch (IOException ioe){
message = "ERROR";
}
finally{
// freeing up i/o streams and http connection
try{
if (hc != null)
hc.close();
}
catch (IOException ignored){}
try{
if (dis != null)
dis.close();
}
catch (IOException ignored){}
try{
if (dos != null)
dos.close();
}
catch (IOException ignored){}
}
return message;
}

Resources