multiple upload images file using httpurlconnection - java

I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
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);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.

Related

Http UrlConnection Java for File Download

We have to connect to a asp.net server to download media items.
We've got this code:
URLConnection urlConnection;
try {
String localTempPath = SettingsManager.getInstance().getLocalTempMediaItemFilePath(loadingItem);
URL serverPath = new URL(SettingsManager.getInstance().getServerMediaItemFilePath(loadingItem));
urlConnection = serverPath.openConnection();
String urlParameters = "http://tempuri.org/";
HttpURLConnection connection = (HttpURLConnection) serverPath.openConnection();
connection.setFollowRedirects(true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
for (String cookie:cookies.keySet()) {
connection.setRequestProperty("Cookie", cookie + "=" + cookies.get(cookie));
} //only one Cookie: ASPNET_SessionId=...
connection.connect();
int response = connection.getResponseCode();
File f = new File (localTempPath);
f.createNewFile();
if (f.exists()){
FileOutputStream fileOutput = new FileOutputStream(f);
//Get Response
InputStream is = connection.getInputStream();
int totalsize = connection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte [1024];
int bufferLength = 0;
while ((bufferLength = is.read(buffer)) > 0){
fileOutput.write(buffer,0,bufferLength);
downloadedSize += bufferLength;
}
fileOutput.close();
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
}
We have to send the Session-Cookie to the server but we always get a 404:java.io.FileNotFoundException: http://possuite.emmgt.at/v30/dataservice/MediaItem/6629.mi

Download File with URL Connection

I have following code, it downloads the file, but Adobe says that the file is damage. The file is 74KB big, but I can only download about 27KB. Can you tell me what's wrong. Thanks
#WebServlet("/GetData")
public class GetData extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int BUFFER_SIZE = 4096;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String typ = ".pdf";
int totalBytesRead = 0;
String sep = File.separator;
String saveDir = "C:" + sep + "downloads";
String link ="/g02pepe/portal?token=9059829732446568452&action_16502593.mainContent_root_cntXYZ_cntShow_actShowFirstRow::km_XXXXXXX-XXXX::=&frontletId=XXXXX";
String adress = "https://XXXXXXX.XXXX.de/g02pepe/entry?rzid=XC&rzbk=0032&trackid=piwikad277d23c35b4990";
String together = adress + link;
String username = "XXXXXXXXX";
String password = "XXXXXXXXX";
String authString = username + ":" + password;
System.out.println("Auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
try {
URL url = new URL(adress);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.addRequestProperty("Referer", together);
System.out.println("Connected to " + together);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
int responseCode = connection.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = adress.substring(adress.lastIndexOf("/") + 1,
adress.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
InputStream in = connection.getInputStream();
String saveFilePath = saveDir + File.separator + "Entgeltinformationen" + typ;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
System.out.println("Total Bytes read " + totalBytesRead);
outputStream.close();
in.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
connection.disconnect();
out.println("Download done!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The file which i want to download is PDF.

Http call crashes

When i call the http, and during it connection is cutt of..my app crashes.. how can i handle such issue in this code?
This also happens when there is no connection, and the http is called.. also it happens when i returns wrong format ( not json)..
HttpConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
// construct the URL
String serverURL = "xxxxxxxxxxxxxxxxxxxxxxx"+Common.getConnectionType();
// encode the parameters
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
byte[] postDataBytes = postData.getBytes();
// construct the connection
conn = (HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "BlackBerry/" + DeviceInfo.getDeviceName() + " Software/" + DeviceInfo.getSoftwareVersion() + " Platform/" + DeviceInfo.getPlatformVersion());
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", new Integer(postDataBytes.length).toString());
// write the parameters
os = conn.openOutputStream();
os.write(postDataBytes);
// write the data and get the response code
int rc = conn.getResponseCode();
if(rc == HttpConnection.HTTP_OK) {
// read the response
ByteVector buffer = new ByteVector();
is = conn.openInputStream();
long len = conn.getLength();
int ch = 0;
// read content-length or until connection is closed
if( len != -1) {
for(int i =0 ; i < len ; i++ ) {
if((ch = is.read()) != -1) {
buffer.addElement((byte)ch);
}
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
buffer.addElement((byte)ch);
}
}
// set the response
accountsResponse = new String(buffer.getArray(), "UTF-8");
} else {
accountsResponse = null;
}
} catch(Exception e){
accountsResponse = null;
} finally {
try {
os.close();
} catch (Exception e) {
// handled by OS
}
try {
is.close();
} catch (Exception e) {
// handled by OS
}
try {
conn.close();
} catch (Exception e) {
// handled by OS
}
}

How to send an audio file to server in android?

public static String fileUploadFromPath(String url, String path) throws Throwable {
System.out.println("IN fileUploadFromPath ");
String responseData = "";
String NL = System.getProperty("line.separator");
try {
System.out.println("url ************ " + url);
File file = new File(path);
System.out.println("file ************ " + file.getAbsolutePath()
+ " : " + file.exists());
StringBuilder text = new StringBuilder();
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append(NL);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
// System.out.println("postRequest ************ " +
// postRequest);
MultipartEntity multipartContent = new MultipartEntity();
ByteArrayBody key = new ByteArrayBody(text.toString()
.getBytes(), AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp");
multipartContent.addPart(AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp", key);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String content = "";
while ((content = in.readLine()) != null) {
sb.append(content + NL);
}
in.close();
/*
* File myDir = new File(Constants.dirctory); if
* (!myDir.exists()) { myDir.mkdirs(); } File myFile = new
* File(myDir, fileName); FileOutputStream mFileOutStream = new
* FileOutputStream(myFile);
* mFileOutStream.write(sb.toString().getBytes());
* mFileOutStream.flush(); mFileOutStream.close();
*/
System.out.println("response " + sb);
}
} catch (Throwable e) {
System.out.println("Exception In Webservice ----- " + e);
throw e;
}
return responseData;
}
I want to upload an audio file into server.
I am able upload audio file to server through above code but the file is not working(not playing in system). If u have any idea please help me.
You should be using neither FileReader nor StringBuilder here as it treats the data as characters (encoded according to the default system character set). Really, you should not be using a Reader at all. Binary data should be handled via InputStream, e.g.
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final InputStream in = new FileInputStream(file)) {
final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
final byte[] data = out.toByteArray();
Did you check checksum on server? Is it arriving unmodified?
If not, try other method to post files. This one helped me a lot:
/**
* Post request (upload files)
* #param sUrl
* #param params Form data
* #param files
* #return
*/
public static HttpData post(String sUrl, Hashtable<String, String> params, ArrayList<File> files) {
HttpData ret = new HttpData();
try {
String boundary = "*****************************************";
String newLine = "rn";
int bytesAvailable;
int bufferSize;
int maxBufferSize = 4096;
int bytesRead;
URL url = new URL(sUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
//dos.writeChars(params);
//upload files
for (int i=0; i<files.size(); i++) {
Log.i("HREQ", i+"");
FileInputStream fis = new FileInputStream(files.get(i));
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data; "
+ "name="file_"+i+"";filename=""
+ files.get(i).getPath() +""" + newLine + newLine);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
fis.close();
}
// Now write the data
Enumeration keys = params.keys();
String key, val;
while (keys.hasMoreElements()) {
key = keys.nextElement().toString();
val = params.get(key);
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data;name=""
+ key+""" + newLine + newLine + val);
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
}
dos.flush();
BufferedReader rd = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
ret.content += line + "rn";
}
//get headers
Map<String, List<String>> headers = con.getHeaderFields();
Set<Entry<String, List<String>>> hKeys = headers.entrySet();
for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
Entry<String, List<String>> m = i.next();
Log.w("HEADER_KEY", m.getKey() + "");
ret.headers.put(m.getKey(), m.getValue().toString());
if (m.getKey().equals("set-cookie"))
ret.cookies.put(m.getKey(), m.getValue().toString());
}
dos.close();
rd.close();
} catch (MalformedURLException me) {
} catch (IOException ie) {
} catch (Exception e) {
Log.e("HREQ", "Exception: "+e.toString());
}
return ret;
}
This is taken from:
http://moazzam-khan.com/blog/?p=490
Check link for dependencies and usage.

unable to upload file great than 1KB in blackberry

private final class ServerConnectThread2 extends Thread
{
private InputStreamReader _in=null;
private OutputStreamWriter _out=null;
private String _url;
private int _delay;
private String _key;
private String _connectionParameters;
OutputStream os=null;
FileConnection fconn=null;
ServerConnectThread2()
{
_key="";
}
public void run()
{
// check internet connection available
setConnectionStringParameter();
bulkUploaderFlag=true;
HttpConnection connection = null;
try
{
_url="http://xxx/bulkuploader.jsp";
_url= EncodeURL (_url) ;
_url = _url + _connectionParameters;
URLEncodedPostData _postData = new URLEncodedPostData("",false);
_postData.append("totalRecord",""+totalRecord);
int count=0;
while( count < totalRecord)
{
_postData.append("accountID"+count,"C"+(String)accountIDVector.elementAt(count));
_postData.append("deviceID"+count,(String)deviceIDVector.elementAt(count));
_postData.append("timestamp"+count,(String)timestampVector.elementAt(count));
_postData.append("statusCode"+count,(String)statusCodeVector.elementAt(count));
_postData.append("latitude"+count,(String)latitudeVector.elementAt(count));
_postData.append("longitude"+count,(String)longitudeVector.elementAt(count));
_postData.append("gpsAge"+count,(String)gpsAgeVector.elementAt(count));
_postData.append("speedKPH"+count,(String)speedKPHVector.elementAt(count));
_postData.append("heading"+count,(String)headingVector.elementAt(count));
_postData.append("altitude"+count,(String)altitudeVector.elementAt(count));
_postData.append("transportID"+count,(String)transportIDVector.elementAt(count));
//_postData.append("inputMask",""+0);
count++;
}
byte [] postDataBytes = _postData.getBytes();
// Open the connection
connection = (HttpConnection)Connector.open(_url, Connector.READ_WRITE, false);
// Set the request method as GET
connection.setRequestMethod("POST");
//connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//connection.setRequestProperty("Content-Type","application/octet-stream");
//connection.setRequestProperty("Content-Type","multipart/form-data");
String len =new String(postDataBytes);
System.out.println(len);
connection.setRequestProperty("Content-Length",""+len.length());
os= connection.openOutputStream();
os.write(postDataBytes);
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2 ]");
int rc = connection.getResponseCode();
if(rc == HttpConnection.HTTP_OK)
{
_in = new InputStreamReader(connection.openInputStream());
// Wait for an acknowledgment, in this case an '1' character, for 'Received'.
//char c = (char)_in.read();
int length=0;
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http==OK ]\n");
StringBuffer buf = new StringBuffer();
while ((length = _in.read()) != -1) {
char c = (char)length;
buf.append(c);
if(c=='0')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==0,not send in bulk unsucessfully ]\n");
System.out.println("DATA not send in bulk SUCCESSFULLY sct2, c==0");
break;
}
if(c=='1')
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, c==1, send in bulk successfully ]\n");
System.out.println("DATA send in bulk SUCCESSFULLY sct2");
String fullPath = "file:///SDCard/dataLog.txt";
try
{
fconn = (FileConnection) Connector.open(fullPath, Connector.READ_WRITE);
if (fconn.exists())
fconn.delete();
}
catch(Exception e){}
finally
{
if(fconn!=null)
fconn.close();
}
break;
}
}
}
else
{
System.out.println("DATA not send in bulk SUCCESSFULLY sct2");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, http not ok ]\n");
}
}
catch (Exception e)
{
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() +", sct2, exception catch ]\n");
exceptionLogObj.saveLog(" [ "+System.currentTimeMillis() + ", "+e.getMessage()+" ] \n");
System.out.println("DATA not send in bulk SUCCESSFULLY"+e.getMessage());
}
finally
{
try
{
if(_in!=null)
_in.close();
if(_out!=null)
_out.close();
if(os!=null)
os.close();
if(connection!=null)
connection.close();
bulkUploaderFlag=false;
}
catch (IOException ioe)
{
// Do Nothing
}
return;
}
}
I think , you must call "dos.flush()" method. My code runs perfectly, postContent is string buffer and contanins 300KB string.
if (getPostContent() == null) {
httpConnection.setRequestMethod(HttpConnection.GET);
} else {
String type = "application/x-www-form-urlencoded";
byte[] bytes = postContent.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Type", type);
httpConnection.setRequestProperty("Content-Length", bytes.length + "");
httpConnection.setRequestMethod(HttpConnection.POST); //setupPost method for this conn
DataOutputStream dos = new DataOutputStream(httpConnection.openOutputStream());
dos.write(bytes);
dos.flush();
dos.close();
}

Categories

Resources