I am trying to create http client for simple service testing. In server side code parameters are getting read by parsing request as mentioned below. I want to set some parameters so that fields will have those parameters
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fields = upload.parseRequest(request);
But I am not able to set parameters those from http client so that value of fields is always empty. I am trying following code
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Content-Type",
"multipart/form-data; boundary=----WebKitFormBoundaryv1eAhALrGwBQXRIp");
httpPost.setHeader("Host", "localhost:8080");
httpPost.setHeader(
"User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("test", "red"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
CloseableHttpResponse response = httpClient.execute(httpPost);
} catch (Exception e) {
}
Please suggest if I am doing something wrong.
Here addFormField() method would do the trick for you. Using addFormField(), the parameter set will be received in your field variable.
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
public static void main(String[] args) {
String charset = "UTF-8";
File uploadFile1 = new File(filename);
String requestURL = url;
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Related
I want to send an audio file to a server via a POST request in my Java Android App. The following code is what I currently have, however, it is not working.
I have found this class implementing a MultiPart Utility:
public class MultipartUtility {
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private final String boundary;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
and want to send a POST request to a server with this client code:
String requestURL = "http://0.0.0.0:5000/test";
try {
com.eng.elfarsisy.recored.MultipartUtility multipart = new com.eng.elfarsisy.recored.MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
However I am getting this response:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.net.SocketException: Permission denied
How can I fix this? Any ideas would be greatly appreciated.
Have you added this permission to your manifest?
<uses-permission android:name="android.permission.INTERNET"/>
I am implementing azure for my web application and trying to get access token by following there openId connect tutorial
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
And when i am requesting to get the access token, i am always getting bad request 400
Request to get access token :
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPl.......
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
here is my code :
public static String post( String endpoint,
Map<String, String> params) {//YD
StringBuffer paramString = new StringBuffer("");
//if(!Utilities.checkInternetConnection(context)){
// return XMLHandler.getXMLForErrorCode(context, JSONHandler.ERROR_CODE_INTERNET_CONNECTION);
//}
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
StringBuffer tempBuffer = new StringBuffer("");
String paramval;
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
if (param != null) {
if (paramString.length() > 0) {
paramString.append("&");
}
System.out.println( "post key : " + param.getKey());
String value;
try {
paramval = param.getValue();
if(paramval!=null)
value = URLEncoder.encode(paramval, "UTF-8");
else
value = "";
} catch (UnsupportedEncodingException e) {
value = "";
e.printStackTrace();
}
paramString.append(param.getKey()).append("=")
.append(value);
}
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(endpoint);
String data = "";
try {
// Add your data
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))
//httppost.addHeader("Host", host);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
if (!paramString.equals("")) {
if (tempBuffer.length() > 0) {
data = data + tempBuffer.toString();
}
data = data + paramString.toString();
if (data.endsWith("&")) {
data = data.substring(0, data.length() - 1);
}
httppost.setEntity(new ByteArrayEntity(data.getBytes()));
}
System.out.println( "post Stringbuffer : " + data);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int statuscode = response.getStatusLine().getStatusCode();
System.out.println("Response code : " + statuscode);
if (statuscode != 200) {
return null;
}
HttpEntity entity = response.getEntity();
InputStream in = null;
if (entity != null) {
in = entity.getContent();
}
if (in != null) {
StringBuilder builder = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
in.close();
}
String response2 = builder.toString();
System.out.println("response :" + response2);
retrycount = 0;
return response2;
}
}
catch(UnknownHostException e){
e.printStackTrace();
return null;
}
catch (EOFException eof) {
if (retrycount < max_retry) {
eof.printStackTrace();
post( endpoint, params);
retrycount = 1;
}
} catch (Throwable th) {
throw new IOException("Error in posting :" + th.getMessage());
}
retrycount = 0;
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Please help me with this
Thanks in Advance
Have you ensured the redirect uri passed to /token is the same as the one you passed to /authorize
I believe, it will help if you can test the OAuth auth code flow with your current client id, secret and scope using Postman tool in order to rule out bad configuration.
Please refer to the code below to request AuthorizationCode.
public static void getAuthorizationCode() throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId
+ "&response_type=" + reponseType
+ "&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F"
+ "&response_mode=query"
+ "&resource=https%3A%2F%2Fgraph.windows.net"
+ "&state=12345";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/authorize";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Then you could get access token using the AuthorizationCode you got and get refresh code using the code below.
public static void getToken(String refreshToken) throws IOException {
String encoding = "UTF-8";
String params = "client_id=" + clientId + "&refresh_token=" + refreshToken
+ "&grant_type=refresh_token&resource=https%3A%2F%2Fgraph.windows.net";
String path = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
byte[] data = params.getBytes(encoding);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setConnectTimeout(5 * 1000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
BufferedReader br = null;
if (conn.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
Hope it helps you.
I'm trying to upload my file to node.js server with javaFX
This code is for node.js server to upload my file.
Simplified my code.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var methodOverride = require('method-override');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var argv = require('optimist').argv;
var fs = require('fs');
app.use('/js', express.static(__dirname + '/js'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
var busboy = require('connect-busboy');
app.use(busboy());
var fileupload = require('fileupload').createFileUpload('/home/kimmj8409/Myweb_front_end').middleware
app.post('/upload', fileupload, function(req, res) {
res.send(req.body);
})
app.listen(8080, argv.fe_ip);
console.log("App listening on port 8080");
and It is javacode to connect with this node.js server
MultipartUtility.java
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Main code :
private void TCP_File_Client() throws IOException{
String url = PATH +"/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File(data_n3_PATH);
File binaryFile = new File(data_n3_PATH);
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
URLConnection connection = new URL(url).openConnection();
HttpURLConnection http = (HttpURLConnection) connection;
http.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
File uploadFile1 = new File(data_n3_PATH);
File uploadFile2 = new File(data_n3_PATH);
String requestURL = PATH +"/upload";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
multipart.addFilePart("fileUpload", uploadFile2);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
With debugging my code, I found that POST request can go to node.js server, but I can not find file.
req.files is empty and I can not find anything looks like file in req.
and I receive IOException("Server returned non-OK status: " + status); with 500 status
How can I connect these?
read https://github.com/expressjs/multer/issues/345.
You can you node.js module multer.
Ive done a service that should download a excelfile and pass in on to the user.
The download method:
private void fetchCompanyInfo(int id) throws IOException{
URL url = new URL("https://xxxxxxxxxx");
URLConnection con = url.openConnection();
String query = "ID="+java.net.URLEncoder.encode(String.valueOf(id),"UTF-8");
String cookie = "";
for (String tmp: this.cookies)
{
System.out.println(tmp);
cookie += tmp.split(";")[0] + ";";
System.out.println(cookie);
}
con.setRequestProperty(COOKIE, cookie);
System.out.println("this is the cookie: " + cookie);
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(query);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String receive = "";
do {
String line = in.readLine();
if (line == null)
break;
receive += line;
} while (true);
in.close();
excel = receive;
System.out.println(receive);
}
And this is the controller:
#RequestMapping(value="/test", produces="application/x-msexcel")
public CompanyInfo test() throws IOException {
return new CompanyInfo();
}
The response from the site im calling returns an
Content-Disposition: attachment; filename=Company123.xls;
Content-Type: Application/x-msexcel
So I just want to forward that attachment
I am using this tutorial to upload large files but it is unable to upload even 300KB of file. Also it does not upload anything other than *.txt or *.log files. Need pointers which can help me upload large files irrespective of filetypes.
Sharing modified code
public class MultipartUtility {
private final String boundary
private static final String LINE_FEED = "\r\n"
private HttpURLConnection httpConn
private String charset
private OutputStream outputStream
private PrintWriter writer
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "==="
URL url = new URL(requestURL)
httpConn = (HttpURLConnection) url.openConnection()
httpConn.setUseCaches(false)
httpConn.setDoOutput(true) // indicates POST method
httpConn.setDoInput(true)
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary)
httpConn.setRequestProperty("User-Agent", "CodeJava Agent")
httpConn.setRequestProperty("Test", "Bonjour")
outputStream = httpConn.getOutputStream()
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true)
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED)
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED)
writer.append(LINE_FEED)
writer.append(value).append(LINE_FEED)
writer.flush()
}
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName()
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED)
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED)
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED)
writer.append(LINE_FEED)
writer.flush()
FileInputStream inputStream = new FileInputStream(uploadFile)
byte[] buffer = new byte[4096]
int bytesRead = -1
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
inputStream.close()
writer.append(LINE_FEED)
writer.flush()
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED)
writer.flush()
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>()
writer.append(LINE_FEED).flush()
writer.append("--" + boundary + "--").append(LINE_FEED)
writer.close()
// checks server's status code first
int status = httpConn.getResponseCode() //<- Exception coming in this line java.io.IOException: Error writing to server
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()))
String line = null
while ((line = reader.readLine()) != null) {
response.add(line)
}
reader.close()
httpConn.disconnect()
} else {
throw new IOException("Server returned non-OK status: " + status)
}
return response
}
static main(args) {
String charset = "UTF-8";
File uploadFile1 = new File("C:\\1392943434245.xml");
String requestURL = "http://localhost:10060/testme";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Have you checked that your HTTP server does not impose a size limit on requests ?
Is there enough memory and disk size ?
Maybe the cause is not in your code.
Try this code, you can be able to upload any file type
public class TryFile {
public static void main(String[] ar) throws HttpException, IOException, URISyntaxException {
// TODO Auto-generated method stub
TryFile t=new TryFile();
t.method();
}
public void method() throws HttpException, IOException, URISyntaxException
{
String url="<your url>";
String fileName="<your file name>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("end"+resEntity.getContentLength());
}
}
This is a working code for file upload:
<jsp:useBean id="upBean" scope="session" class="javazoom.upload.UploadBean" >
<jsp:setProperty name="upBean" property="filesizelimit" value="<%= 1024 * 1024%>" />
</jsp:useBean>
try this,
try {
if (MultipartFormDataRequest.isMultipartFormData(request)) {
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
Hashtable files = mrequest.getFiles();
byte data[] = null;
if ((files != null) && (!files.isEmpty())) {
fileObj = (UploadFile) files.get("fileUpload");
m_imagename = fileObj.getFileName().trim();
//File type validator
if (!Utility.isValiedFileName1(m_imagename)) {
ERROR = "Invalid File Type";
response.sendRedirect("XXX.jsp");//response page
return;
}
//file uploader method call
if ((fileObj != null) && (fileObj.getFileName() != null)) {
data = fileObj.getData();
//Java method for uploading
result = imageUpload.copyImage(data);//depCode
}
}
}
} catch (Exception e) {
SystemMessage.getInstance().writeMessage(" ERROR : " + e);
}
This is part related to HTTP.
Refer
here
We can upload any number of files of any sizes using plupload.