Why cannot post whole string of base64 using httpurlconnection? - java

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();
?>

Related

Gson ArrayList<different Objsct>

//output
String outStr = "";
ArrayList<DateItemVO> dateItem= dateItemDAO.findItemSeller(memberInteger);
ArrayList<Member> member= new ArrayList<Member>();
ArrayList<Pet> pet= new ArrayList<Pet>();
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
OrderVOAll orderVO = new OrderVOAll(dateItem,member,pet,restaurant);
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
outStr = gson.toJson(orderVO);
rp.setContentType(text/html; charset=UTF-8);
PrintWriter out = rp.getWriter();
out.println(outStr);
//input
jsonIn = getRemoteImage(url, jsonObject.toString());
private String getRemoteImage(String url, String jsonOut) throws IOException {
StringBuilder jsonIn = new StringBuilder();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true); // allow inputs
connection.setDoOutput(true); // allow outputs
connection.setUseCaches(false); // do not use a cached copy
connection.setRequestMethod("POST");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bw.write(jsonOut);
Log.d(TAG, "jsonOut: " + jsonOut);
bw.close();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine())!=null){
jsonIn.append(line);
}
Log.d(TAG, "jsonInqq: " + jsonIn);
} else {
Log.d(TAG, "response code: " + responseCode);
}
connection.disconnect();
return jsonIn.toString();
}
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return gson.fromJson(jsonIn,OrderVOAll.class);
the other side when i catch the json i got an errer.i can got the message from db ,but i dont know the reason why i got the msgm
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
thanks for help

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

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

HttpURLConnection not reading the whole content

I'm trying to read a website but strangely it returns only part of it. It just ends in the middle of section.
I tried using the setChunkedStreamingMode method but it didn't change anything.
HttpURLConnection connection = ((HttpURLConnection) new URL(url).openConnection());
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
// I write some data...
String content = readInputStream(connection.getInputStream());
ReadInputStream method:
private static String readInputStream(InputStream in) throws IOException {
int len = 0;
byte[] buffer = new byte[10000];
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
while((len = in.read(buffer)) != -1) {
byteArray.write(buffer,0, len);
}
in.close();
return new String(byteArray.toByteArray());
}
Is there some sort of limit of data?
there is no problem with HttpUrlConnection
try this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();

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