Android posting a multipart html form to php server - java

I wrote this AsyncTask class that sends an array of POST data to my php server with no problem. Now I want to extend it so that it also sends a file to same script (I have already the receive handling in the php file). What I mean is I want it to post DATA + FILE in one go. Something like multipart entity or something from HTML action to php script.
What would I need to add to this class so it can upload a file with other things?
public class UpdateSnakeGameStatusTask extends AsyncTask<String, Integer, HttpResponse> {
private Context mContext;
private ArrayList<NameValuePair> mPairs;
/**
* #param context The context that uses this AsyncTask thread
* #param postPairs <b>NameValuePair</b> which contains name and post data
*/
public UpdateSnakeGameStatusTask(Context context, ArrayList<NameValuePair> postPairs) {
mContext = context;
mPairs = new ArrayList<NameValuePair>(postPairs);
}
#Override
protected HttpResponse doInBackground(String... params) {
HttpResponse response = null;
HttpPost httppost = new HttpPost(params[0]); //this is the URL
try {
httppost.setEntity(new UrlEncodedFormEntity(mPairs));
HttpClient client = new DefaultHttpClient();
response = client.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}

Ok as #greenapps suggested (credit goes to him) I solved like this.
Well not entirly solved, because I have to decode the file content at server side and save it manually on server.
so I jsut added the file content to the BasicNameValuePair that I already had:
String fileAsBase64 = Base64.encodeToString( convertToByteArray(mFile)
, Base64.DEFAULT);
mPostPairs.add(new BasicNameValuePair("filecontent", fileAsBase64));
And this is the method that converts it to byte array:
/**
* Reads a file and returns its content as byte array
* #param file file that should be returned as byte array
* #return byte[] array of bytes of the file
*/
public static byte[] convertTextFileToByteArray(File file) {
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
}catch(Exception e){
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
fileInputStream = null;
}
}
return bFile;
}
At the server side I do this:
$content = imap_base64 ($_POST["filecontent"]);
that takes care of decoding the content back to normal.
Hope this helps someone else too

Related

Request a map from WMS and save it to the disk as a PNG image

I have to write code using java and GeoTools to do a WMS request, get the image and save it to a specific location on my computer. I've followed the GeoTools WMS tutorial and the code compiles without errors, but I don't know how to check if it had worked or how to save the requested image?
Here is the GetMap request with all the necessary parameters: http://ows.mundialis.de/services/service?request=GetMap&service=WMS&version=1.3.0&layers=OSM-Overlay-WMS&styles=default&crs=EPSG%3A4326&bbox=47.75,12.98,47.86,13.12&&width=2000&height=2000&format=image/png&transparent=true
Here is the code:
public class WmsConnectorMaven {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("http://ows.mundialis.de/services/service?service=wms&version=1.3.0&request=GetCapabilities");
} catch (MalformedURLException e) {
//will not happen
}
WebMapServer wms = null;
try {
wms = new WebMapServer(url);
GetMapRequest request = wms.createGetMapRequest();
request.addLayer("OSM-Overlay-WMS", "defualt");
request.setFormat("image/png");
request.setDimensions("800", "800"); //sets the dimensions of the image to be returned from the server
request.setTransparent(true);
request.setSRS("EPSG:4326");
request.setBBox("47.75,12.98,47.86,13.12");
GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
BufferedImage image = ImageIO.read(response.getInputStream());
/* File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile); */
// FileOutputStream img = new FileOutputStream("C:\\Users\\Edhem\\Desktop\\WMSimage.png");
} catch (IOException e) {
//There was an error communicating with the server
//For example, the server is down
} catch (ServiceException e) {
//The server returned a ServiceException (unusual in this case)
}
}
}
You need to check the contentType of the returned response and make a decision based on that value. Something like:
try {
GetMapResponse response = wms.issueRequest(getMapRequest);
if (response.getContentType().equalsIgnoreCase(format)) {
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} else {
StringWriter writer = new StringWriter();
IOUtils.copy(response.getInputStream(), writer);
String error = writer.toString();
System.out.println(error);
return null;
}
} catch (ServiceException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
UPDATE
I just ran your code with my checks and I get:
<?xml version="1.0"?>
<ServiceExceptionReport version="1.3.0"
xmlns="http://www.opengis.net/ogc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/ogc
http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd">
<ServiceException code="StyleNotDefined">unsupported styles: defualt</ServiceException>
</ServiceExceptionReport>
removing the (misspelt) "defualt" gives (which I guess is right):

Uploading image from android app to Spring server

I have a problem with uploading image from android application to spring server. First of all i have this method on my server:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String fileUpload(#RequestBody MultipartFile file) {
System.out.println("post image");
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
System.out.println(bytes.length);
//save file in server - you may need an another scenario
Path path = Paths.get("file:///E:/together/images/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
//redirect to an another url end point
return "redirect";
}
And in my android app i'am get uri of image from image gallery and try call post method
FileEntity fileEntity = new FileEntity(new File(getRealPathFromURI(uri)), "application/octet-stream");
new Requests.Async().execute(fileEntity);
ublic static class Async extends AsyncTask<FileEntity,Void,Void>{
#Override
protected void onPreExecute() {
restTemplate = RestTemplateSingleton.newInstance().getRestTemplate();
}
#Override
protected Void doInBackground(FileEntity... uris) {
try{
restTemplate.postForObject(Requests.insertImage(),uris[0],FileEntity.class);
}catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
return null;
}
return null;
}
}
but i get 500 http status when call this method. what's my mistake?

JAX-RS - Wink - Correct way to read a file, using Wink Client

Related to this question which is about how to send a binary file to a client. I am doing this, actually my method #Produces("application/zip"), and it works well for the browser client. Now I'm trying to write some automated tests against the rest service, using the Wink client. So my question is not how to send the file to the client, but for how to consume the file, as a java rest client (in this case Apache Wink).
My resource method looks something like the below... Once I have a Wink ClientResponse object, how can I get the file from it so I can work with it?
#GET
#Path("/file")
#Produces("application/zip")
public javax.ws.rs.core.Response getFile() {
filesToZip.put("file.txt", myText);
ResponseBuilder responseBuilder = null;
javax.ws.rs.core.Response response = null;
InputStream in = null;
try {
in = new FileInputStream( createZipFile( filesToZip ) );
responseBuilder = javax.ws.rs.core.Response.ok(in, MediaType.APPLICATION_OCTET_STREAM_TYPE);
response = responseBuilder.header("content-disposition", "inline;filename="file.zip").build();
} catch( FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
return response;
The method that actually creates the zip file looks like this
private String createZipFile( Map<String,String> zipFiles ) {
ZipOutputStream zos = null;
File file = null;
String createdFileCanonicalPath = null;
try {
// create a temp file -- the ZIP Container
file = File.createTempFile("files", ".zip");
zos = new ZipOutputStream( new FileOutputStream(file));
// for each entry in the Map, create an inner zip entry
for (Iterator<Map.Entry<String, String>> it = zipFiles.entrySet().iterator(); it.hasNext();){
Map.Entry<String, String> entry = it.next();
String innerFileName = entry.getKey();
String textContent = entry.getValue();
zos.putNextEntry( new ZipEntry(innerFileName) );
StringBuilder sb = new StringBuilder();
byte[] contentInBytes = sb.append(textContent).toString().getBytes();
zos.write(contentInBytes, 0, contentInBytes.length);
zos.closeEntry();
}
zos.flush();
zos.close();
createdFileCanonicalPath = file.getCanonicalPath();
} catch (SecurityException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return createdFileCanonicalPath;
}
You can consume it simply as input stream and use ZipInputStream to unzip it.
Here's example using Apache HTTP Client:
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.addHeader(new BasicHeader("Accept", "application/zip"));
HttpResponse response = httpclient.execute(get);
InputStream is = response.getEntity().getContent();
ZipInputStream zip = new ZipInputStream(is);

Difficulty in receiving response from HTTP client

I am writing an application which will send XML over HTTP to a server, and receive XML as the response. I am able to send XML to the server but not able to receive the response.
This is my client code:
public void sendXMLToServer(){
System.out.println("sendXMLToServer");
String strURL = "http://localhost:9080/MockServerMachine/sendXMLPost";
// Get file to be posted
String strXMLFilename = "output.xml";
File input = new File(strXMLFilename);
// Prepare HTTP post
System.out.println("junaud url "+ strURL);
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
try {
post.setRequestHeader("Content-type","application/xml");
post.setRequestHeader("Accept","application/xml");
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
HttpClient httpclient = new HttpClient();
int result = httpclient.executeMethod(post);
String xmlResponse = post.getResponseBodyAsString();
// Display status code
System.out.println("Response status code jun: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is the server side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//InputStream in = request.getInputStream();
//URL xmlUrl = new URL(request.getRequestURL().toString());
//InputStream in = xmlUrl.openStream();
response.setContentLength(100);
// PostMethod po = new PostMethod(request.getRequestURL().toString());
// System.out.println("kikmk = "+po.getRequestEntity());
try {
// read this file into InputStream
//InputStream inputStream = new FileInputStream("c:\\file.xml");
InputStream inputStream = request.getInputStream();
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File("c:\\junaidAhmedJameel.xml"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
System.out.println(new String (bytes));
System.out.println(read);
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Can anyone help me out here? Any sample client/server example for sending XML over HTTP would be great.
Ah, spotted it. Look here:
OutputStream out = new FileOutputStream(new File("c:\\junaidAhmedJameel.xml"));
That's just going to write to the local disk. You're not writing any content to the response stream. It's not clear what you want to write to the response stream, but there's a conspicuous absence of calls to response.getWriter() or response.getOutputStream().
You're setting the content length to 100, but not actually sending any content. Note that hard-coding the content-length is almost certainly the wrong thing to do anyway... but it's definitely the wrong thing to do when you're not sending any content...
You never generate any response content in your server code. You just set the length to 100.

How to send zipped http request?

I want to send a zipped request body as a POST http request for a web-service based application. Can anybody please help me how can I send a zipped http request or how can i send a zipped request body as part of POST http request?
Edit: Adding the solution here
HttpURLConnection request = null;
StringBuilder sb = new StringBuilder(getFileAsString("TestFile.txt"));
String fileStr = getFileAsString("TestFile.txt");
HttpClient client = new HttpClient();
client.getState().setCredentials(
new AuthScope(hostip, port),
new UsernamePasswordCredentials("username", "password"));
PutMethod post = new PutMethod(url);
post.setRequestHeader("Content-Encoding", "gzip")
HTTP protocol doesn't support compressed requests (it does support compressed responses being exchanged where the client would announce its ability to handle compressed content). If you want to implement compressed requests, then such a protocol should be established between the client and your web-service that the HTTP payload is always compressed so that on the receiving side, the web service can always decompress and interpret the payload.
public static void main(String[] args) throws MessagingException,
IOException {
HttpURLConnection request = null;
try {
// Get the object of DataInputStream
StringBuilder sb = new StringBuilder(getFileAsString("TestFile.txt"));
String fileStr = getFileAsString("TestFile.txt");
System.out.println("FileData=" + sb);
HttpClient client = new HttpClient();
client.getState().setCredentials(
new AuthScope(hostip, portno),
new UsernamePasswordCredentials(username, password));
PutMethod post = new PutMethod(url);
post.setRequestHeader("Content-Encoding", "gzip");
post.setRequestHeader("Content-Type", "application/json");
post.setDoAuthentication(true);
byte b[] = getZippedString(fileStr);;
InputStream bais = new ByteArrayInputStream(b);
post.setRequestBody(bais);
try {
int status = client.executeMethod(post);
} finally {
// release any connection resources used by the method
post.releaseConnection();
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
I use a special servlet that decompress and compress the requests and responses
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException{
InputStream zipedStreamRequest = req.getInputStream();
String unzipJsonStr = ZipUtil.uncompressWrite(zipedStreamRequest);
System.out.println("<---- ZIP request <----");
System.out.println(unzipJsonStr);
MainHandler handler = new MainHandler();
String responseJson = handler.handle(unzipJsonStr);
System.out.println("----> ZIP response ---->");
System.out.println(responseJson);
OutputStream responseOutputStream = res.getOutputStream();
if (responseJson!=null) {
ZipUtil.compressWrite(responseJson, responseOutputStream);
}
}
then here is my ziputil class
public class ZipUtil {
private static final int NB_BYTE_BLOCK = 1024;
/**
* compress and write in into out
* #param in the stream to be ziped
* #param out the stream where to write
* #throws IOException if a read or write problem occurs
*/
private static void compressWrite(InputStream in, OutputStream out) throws IOException{
DeflaterOutputStream deflaterOutput = new DeflaterOutputStream(out);
int nBytesRead = 1;
byte[] cur = new byte[NB_BYTE_BLOCK];
while (nBytesRead>=0){
nBytesRead = in.read(cur);
byte[] curResized;
if (nBytesRead>0){
if (nBytesRead<NB_BYTE_BLOCK){
curResized = new byte[nBytesRead];
System.arraycopy(cur, 0, curResized, 0, nBytesRead);
} else {
curResized = cur;
}
deflaterOutput.write(curResized);
}
}
deflaterOutput.close();
}
/**
* compress and write the string content into out
* #param in a string, compatible with UTF8 encoding
* #param out an output stream
*/
public static void compressWrite(String in, OutputStream out){
InputStream streamToZip = null;
try {
streamToZip = new ByteArrayInputStream(in.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
ZipUtil.compressWrite(streamToZip, out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* uncompress and write int into out
* #param in
* #param out
* #throws IOException
*/
private static void uncompressWrite(InputStream in, OutputStream out) throws IOException{
InflaterInputStream inflaterInputStream = new InflaterInputStream(in);
int nBytesRead = 1;
byte[] cur = new byte[NB_BYTE_BLOCK];
while (nBytesRead>=0){
nBytesRead = inflaterInputStream.read(cur);
byte[] curResized;
if (nBytesRead>0){
if (0<=nBytesRead && nBytesRead<NB_BYTE_BLOCK){
curResized = new byte[nBytesRead];
System.arraycopy(cur, 0, curResized, 0, nBytesRead);
} else {
curResized = cur;
}
out.write(curResized);
}
}
out.close();
}
/**
* uncompress and write in into a new string that is returned
* #param in
* #return the string represented the unziped input stream
*/
public static String uncompressWrite(InputStream in){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
uncompressWrite(in, bos);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
byte[] byteArr = bos.toByteArray();
String out = new String(byteArr, "UTF-8");
return out;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}

Categories

Resources