Http UrlConnection Java for File Download - java

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

Related

Why cannot post whole string of base64 using httpurlconnection?

I want to upload the image to the server.
I got the bitmap of the image and encoded it to base64.
I convert the base64 of the image to a string using the encodeToString method.
I post the string to PHP using httpurlconnection. Actually, I got the string from PHP which is not the whole string. I don`t get any error. Please give me feedback!
public String httpURLConnectionPost(final String urlString){
String result="";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_CLOSE);
String body= "image="+encodedImage;
Log.d("serverPostData","body = " +body);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
The php got the string and decode it.
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($image));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>
Try this to convert image to base64:
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
String encodedImageData = getEncoded64ImageStringFromBitmap(bitmap);
Now pass the data in API:
JsonObject data1 = new JsonObject();
data1.addProperty("imageData", "data:image/png;base64," + encodedImageData);
Now set ImageBitmap:
image.setImageBitmap(bitmap);
Here is the method:
private String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
And for HttpUrlConnection try this...
jsonObject = new JSONObject();
jsonObject.put("imageString", encodedImage);
String data = jsonObject.toString();
String yourURL = "yourphpfileurl";
URL url = new URL(yourURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(data.getBytes().length);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
in.close();
String result = sb.toString();
connection.disconnect();
Hope this one will work for you...
I solved my probelm that the base64 need to replace empty to "+".
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$change = str_replace(" ","+",$image);
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($change ));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>

multiple upload images file using httpurlconnection

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.

in java how to copy data from file in the URL into excel worksheet

i am working on a system and need to fetch file from the URL using java URLConnection, Now all i need to copy that contents into excel file.
here is my code.
class getsize {
public static void main(String args[]) throws Exception {
HttpURLConnection conn = null;
try {
String plainCreds = "hmhinstall:hmh201208";
// String url = "http://content.link-systems.com/~hbern/content_update/";
byte[] plainCredsBytes = plainCreds.getBytes();
String base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = base64CredsBytes;
System.out.println(base64Creds);
int code = 0;
URL url = new URL("http://content.link-systems.com/~hbern/content_update/ ");
//Reading
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine); //Printing file data
}
in.close();
//Getting size
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + base64Creds);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
System.out.println(conn.getResponseCode());
System.out.println(conn.getContentType());
conn.getInputStream();
System.out.println("Length : " + conn.getContentLength()); //Getting content length
} catch (Exception exception) {
} finally {
conn.disconnect(); //Disconnect
}
}
}
How can i copy contents of a file in to excel worksheet? So that i can generate records automatically.
thanks in advance

What should i use InputStream or FileInputStream or BufferedInputStream?

I am downloading few pdf and video file from the server and for that I am using InputStream to collect response but I want to know that which is better for my purpose InputStream or FileInputStream or BufferedInputStream ?
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile, fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
I am using this for downloading videos
void downloadFile(String vidN){
int downloadedSize = 0;
int totalSize = 0;
try {
// here vidN is the name of the file like bird.mp4
// here sitepath is the path of the file
URL url = new URL(sitepath+vidN);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "VideoNR2";
File RootFile = new File(RootDir);
RootFile.mkdir();
//create a new file, to save the downloaded file
File file = new File(RootDir,""+vidN);
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize = bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
}
}

How to through a java application to transfer data to the servlet

I want to pass a java application sent a string that is a json,it isn't get this json in servlet, how do I do, who can help me?
This is my servlet code:
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
BufferedInputStream in = new BufferedInputStream(req.getInputStream());
byte[] data = null;
byte[] bts = new byte[1024];
int index;
while ((index = in.read(bts)) >= 0) {
if (data == null) {
data = new byte[index];
System.arraycopy(bts, 0, data, 0, index);
}
else {
byte[] tmp = data;
data = new byte[tmp.length + index];
System.arraycopy(tmp, 0, data, 0, tmp.length);
System.arraycopy(bts, 0, data, tmp.length, index);
}
}
String json = new String(data);
System.out.print(json);
}
and this is my java application:
String _url = "http://localhost:8080/jsf/test";
URL url = null;
HttpURLConnection urlconn = null;
String json = URLEncoder.encode(JSONObject.fromObject(req)
.toString(), "UTF-8");
url = new URL(_url);
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("POST");
urlconn.setDoOutput(true);
urlconn.setDoInput(true);
OutputStream out = urlconn.getOutputStream();
out.write(json.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlconn.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1) {
sb.append((char) ch);
}
System.out.println(sb);
rd.close();
You should write json data to outputStream as out.write(json.getBytes()); . See the complete code below:
String _url = "http://localhost:8080/jsf/test";
URL url = new URL(_url);
String json = "[{\"id\":\"DFAB8108D69642EBBD461160B4519B0F\",\"name\":\"name1\"},{\"id\":\"B048B2521A5619DCE0440003BA11CFDA\",\"name\":\"name2\"}]";
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("POST");
urlconn.setDoOutput(true);
OutputStream out = urlconn.getOutputStream();
out.write(json.getBytes());
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlconn.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1) {
sb.append((char) ch);
}
System.out.println(sb.toString());
rd.close();
Try something like this
String _url = "http://localhost:8080/jsf/test";
URL url = new URL(_url);
String json = "[{\"id\":\"DFAB8108D69642EBBD461160B4519B0F\",\"name\":\"name1\"},{\"id\":\"B048B2521A5619DCE0440003BA11CFDA\",\"name\":\"name2\"}]";
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn .setDoOutput(true);
urlconn .setRequestProperty("Content-Type", "application/json");
urlconn .setRequestProperty("Accept", "application/json");
urlconn .setRequestMethod("POST");
urlconn .connect();
OutputStream os = httpcon.getOutputStream();
os.write((json.getBytes("UTF-8"));
os.close();

Categories

Resources