I am trying to send an String from my android app to the server. The String contains: username, password and a image encoded in base 64. Between them is a space(" "). I am using heroku to store the server and I use a postgreSQL database. I have a table named users with the columns : userid,password, encoded image, all of them in format text.
When I create a new user I give the userid and the password, the column encodedimage is empty. I want to make an update to the table when I want to upload the image to the server and edit the encodedimage column.
Here is how I send the String from android:
request=Utils.name+" "+Utils.password;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
request = request+ " " + Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream outputStream = urlConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(request);
bufferedWriter.flush();
bufferedWriter.close();
outputStreamWriter.close();
outputStream.close();
int response=urlConnection.getResponseCode();
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If I update my table from cmd it works but from code it doesn't.
Here is my controller:
#Controller
public class UploadController implements Constant {
#RequestMapping(value = "/upload-image", method = RequestMethod.POST)
public void handleUploadImageRequest(#RequestBody String request) {
String[] details = request.split(" ");
String name = details[0];
String password = details[1];
byte[] decodedImage = Base64.getDecoder().decode(details[2]);
if (decodedImage.length > 0) {
try {
Image image = ImageIO.read(new ByteArrayInputStream(decodedImage));
Connection connection = null;
Statement statement = null;
String updateUSER = "UPDATE " + TABLE_USERS + " SET " + COLUMN_ENCODEDIMAGE + "='" + details[2]
+ "' WHERE " + COLUMN_USERID + "='" + name + "' AND '" + COLUMN_PASSWORD + "='" + password + "';";
try {
connection = DatabaseUtils.getConnection();
statement = connection.createStatement();
statement.executeUpdate(updateUSER);
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In heroku logs I found:
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void com.rares.controllers.UploadController.handleUploadImageRequest(java.lang.String)
Is the android code ok? Where is the problem or how should I do it. Please don't point me to deprecated methods.
I
Wrong posting. Your request should more look like:
request = "username=" + userName
+ "&password=" + passWord
+ "&image=" + base64String.
And then the values should be url encoded yet.
Related
I'm using this code for bypass the css from WebView loading , I used asset folder for loading my own css but now I need to load my custom css from URL because I need to Change my Css every week .
probelm is : after change InputStream to URL my css bypass is note working !!
My old code is :
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
and My New code is : > but is not working
private void injectCSS() {
try {
final InputStream inputStream = new URL("https://sitemname.ir/app/style.css").openStream();
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
webView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
I am struggling to understand the whole new idea of accessing my organizatioon's Sharepoint content using Sahrepoint REST API and I am trying to implementing it in java. My aim is to read all the files in "abc" folder which is in Documents folder. Steps I did.
Register the app:
Click Generate Client ID,
Click Generate Client Secret,
Gave Title,
Gave Appdomain as companyname.onmicrosoft, and
Gave Request URI as https://companyname.sharepoint.com/Shared%20Documents/Forms/AllItems.aspx
Got the app registered. I have client id, client secret, and tenant id.
I used the below code to generate the access token
public String getSpToken(String shp_clientId, String shp_tenantId, String shp_clientSecret) {
String accessToken = "";
try {
// AccessToken url
String wsURL = "https://accounts.accesscontrol.windows.net/" + shp_tenantId + "/tokens/OAuth/2";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Set header
httpConn.setRequestProperty("Content-Type", " ");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
// Prepare RequestData
String jsonParam = "grant_type=client_credentials"
+ "&client_id=" + shp_clientId + "#" + shp_tenantId
+ "&client_secret=" + shp_clientSecret
+ "&resource=00000003-0000-0ff1-ce00-000000000000/www.companyname.sharepoint.com#" + shp_tenantId;
// Send Request
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(jsonParam);
wr.flush();
wr.close();
// Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String responseString = "";
String outputString = "";
// Write response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Printing the response to the console
System.out.println("Output from the REST" + outputString);
// Extracting accessToken from string, here response (outputString)is a Json format string
if (outputString.indexOf("access_token\":\"") > -1) {
int i1 = outputString.indexOf("access_token\":\"");
String str1 = outputString.substring(i1 + 15);
int i2 = str1.indexOf("\"}");
String str2 = str1.substring(0, i2);
accessToken = str2;
}
//Printing the access token
System.out.println("Access token is " + accessToken);
} catch (Exception e) {
accessToken = "Error: " + e.getMessage();
}
return accessToken;
}
Now that I have the access token in the String variable "accessToken", I used the following code to read the filenames inside the folder "abc" in Documents folder using readFiles() method
public void readFiles(String accessToken) {
try {
//Frame SharePoint siteURL
String siteURL = "https://companyname.sharepoint.com";
//Frame SharePoint URL to retrieve the name of all of the files in a folder
String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents/abc')/Files";
//Create HttpURLConnection
URL url = new URL(wsUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
//Set Header
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
httpConn.setRequestProperty("accept", "application/json;odata=verbose"); //To get response in JSON
//httpConn.setRequestProperty("AllowAppOnlyPolicy", "true");
//httpConn.setRequestProperty("Scope", "http://sharepoint/content/sitecollection/web\" Right=\"FullControl");
//Read the response
String httpResponseStr = "";
InputStreamReader isr = null;
System.out.println(httpConn.getResponseCode());
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
} else {
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String strLine = "";
while ((strLine = in.readLine()) != null) {
httpResponseStr = httpResponseStr + strLine;
}
//Print response
System.out.println(httpResponseStr);
} catch (Exception e) {
System.out.println("Error while reading file: " + e.getMessage());
}
}
}
When I execute the above code I am getting {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}. Could someone please help me to figure out what I am doing wrong? I have been sitting on this for days and not able to resolve it.
Please help!
on address bar : http://localhost:8080/tryupload/downloadservlet?bookid=15bk
bookid=15bk (15bk was i got from my bookId on database, by getString on servlet)
then , below is my display on servlet (not jsp)
out.println("<TD>Download</TD>");
then it goes to
downloadservlet.java // but it didnt worked. Blank page.
How read the "boookid " from this link http://localhost:8080/tryupload/downloadservlet?bookid=15bk to my servlet? and be execute on my downloadservlet.java?
downloadservlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String bookId = request.getParameter("bookId");
Connection conn = null; // connection to the database
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// queries the database
String sql = "SELECT * FROM books WHERE bookId = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, bookId);
ResultSet result = statement.executeQuery();
if (result.next()) {
// gets file name and file blob data
String fileName = result.getString("BookContent");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("fileLength = " + fileLength);
ServletContext context = getServletContext();
// sets MIME type for the file download
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
// set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
// writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
// no file found
response.getWriter().print("File not found for the id: " + bookId);
}
} catch (SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch (IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
you read the parameter correctly with
request.getParameter("bookid")
However you cannot apply directly Integer.parseInt as you read 15bk and which is not an integer, if you need 15 out of 15 bk you need an additional step of parsing.
Following your last edit, its the same issue - you cannot do
statement.setInt(1, bookid);
bookid will not be an int. you need to parse, not sure but for example if you want to eliminate the last 2 characters you could do
bookIntId = bookId.substrings(0, bookId.length - 2)
String bookId = request.getParameter("bookid");
If your parameter value is 15bk then your line of code:
int bookid = Integer.parseInt(request.getParameter("bookid"));
Will throw NumberFormatException as bk cannot be converted into an integer value.
I am trying to send HTTPS Post Request from jsp to Opera Server. But I can't. I have found many HTTP Post Request examples but no HTTPS. I am getting an Error Message now..
java.lang.ClassCastException: sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to com.sun.net.ssl.HttpsURLConnection
My import are as follows for this code
java.security.Security, com.sun.net.ssl.
My code as follows
try{
String data = URLEncoder.encode("AccountID", "UTF-8") + "=" + URLEncoder.encode(accountid, "UTF-8");
data += "&" + URLEncoder.encode("CallerTransactionID", "UTF-8") + "=" + URLEncoder.encode(callertransactionid, "UTF-8");
data += "&" + URLEncoder.encode("CurrentTime", "UTF-8") + "=" + URLEncoder.encode(currenttime, "UTF-8");
data += "&" + URLEncoder.encode("ErrorURL", "UTF-8") + "=" + URLEncoder.encode(errorurl, "UTF-8");
//data += "&" + URLEncoder.encode("FrameURL", "UTF-8") + "=" + URLEncoder.encode(frameurl, "UTF-8");
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL opxurl = new URL("https://opx-test.opera.com/opx/2.0/OPXPaymentEnable");
HttpsURLConnection connopx = (HttpsURLConnection) opxurl.openConnection();
connopx.setDoInput(true);
connopx.setDoOutput(true);
connopx.setRequestMethod("POST");
connopx.setFollowRedirects(true);
connopx.setRequestProperty("Content-length",String.valueOf(data.length()));
connopx.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
// open up the output stream of the connection
DataOutputStream output = new DataOutputStream(connopx.getOutputStream());
// write out the data
int dataLength = data.length();
output.writeBytes(data);
//output.flush();
System.out.println("HOly Portal ResponseDesc Code:"+connopx.getResponseCode()+" : "+connopx.getResponseMessage());
// get ready to read the response from the cgi script
DataInputStream input = new DataInputStream( connopx.getInputStream() );
// read in each character until end-of-stream is detected
for( int c = input.read(); c != -1; c = input.read() )
System.out.print("HolyPortal respnse: "+ (char)c );
input.close();
After all connopx's settings you have to call
connopx.connect();
I use this import and it works in my code:
import javax.net.ssl.HttpsURLConnection;
I don't have the two lines above URL opxurl =
Have a look at this answer with similar issue also.
EDIT:
To avoid error 500 remove space in "application/x-www-form-urlencoded" and add those two lines right after output.writeBytes(data);:
output.flush();
output.close();
Then it should work.
This should be your code
try {
URL url = new URL("yourURL");
URLConnection conn = url.openConnection();
if (conn instanceof HttpsURLConnection) {
// Try again as HTTPS
HttpsURLConnection conn1 = (HttpsURLConnection) url.openConnection();
conn1.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn1.getResponseCode();
}
}
catch (MalformedURLException e) {
}
catch (IOException e) {
}
Authentication credentials are set here, everything works perfectly if user/password provided is correct, but it hangs if they are incorrect. It's not the server issues, I checked with Curl and Browser, incorrect credentials return 401 right away.:
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}
});
Code that hangs is here,it hangs on this line: in = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream())); (No exception, it just stays on this line)
try {
URL url = new URL(resourceUrl);
HttpURLConnection httpURLConn = (HttpURLConnection) url.openConnection();
String rawData = "";
String currentLine = null;
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream()));
while ((currentLine = in.readLine()) != null) {
rawData = rawData.concat(currentLine);
}
in.close();
} catch (UnknownHostException e) {
Log.i(CLASS_NAME + "::" + METHOD_NAME
, "An exception occured while reading data from remote host. httpURLConn.responseCode = " + httpURLConn.getResponseCode()
+ " / httpURLConn.responseMessage = " + httpURLConn.getResponseMessage(), e);
throw new UnknownHostException();
} catch (IOException e) {
Log.i(CLASS_NAME + "::" + METHOD_NAME
, "An exception occured while reading data from remote host. httpURLConn.responseCode = " + httpURLConn.getResponseCode()
+ " / httpURLConn.responseMessage = " + httpURLConn.getResponseMessage(), e);
throw new IOException();
}
Could it be that the server is keeping the connection alive (Keep-Alive header)?