How to post a byte code a php website? - java

I have a method can convert to a data to byte array and i must post it to a php web site. I am gonna use a java socket now. preparing that if i did i will add it here
it is data to byte[] methods , i found it in PDF to byte array and vice versa
public static byte[] readFully(InputStream stream) throws IOException
{
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = stream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
}
public static byte[] loadFile(String sourcePath) throws IOException
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(sourcePath);
return readFully(inputStream);
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
Here how to post a byte to php web site...
public static void postMybyte (String out)
{
try {
// Construct data
String data = URLEncoder.encode(out, "UTF-8") ;
// Send data
URL url = new URL("");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(" --->>>>"+line);
}
wr.close();
rd.close();
} catch (Exception e)
{
}
}

Related

Why the file I download via GitHub API has no content?

I am using the GitHub API to fetch files from a repository. I have the functionality implemented and it does work, I download the needed files but I found something strange, out of the 4 files I get, one is empty (no content inside) even though when I go the to repository and open it there it is clearly with content. The rest of the files have their content in when downloaded. Any idea why that happens?
Here is my code:
public int downloadFromGithub(String repo, String fileName) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", ****);
connection.setRequestProperty("Accept", ****);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && fileName!=null)
{
return saveFile(connection, fileName);
}
else { return connection.getResponseCode();}
}
public void downloadMultipleFilesFromGithub(String repo,String directoryPath) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", *****);
connection.setRequestProperty("Accept", "***");
String response = getResponseBody(connection);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray array = jsonObj.getJSONArray("tree");
for (int i=0; i < array.length(); i++) {
System.out.println(array.getJSONObject(i).get("path"));
String path = array.getJSONObject(i).get("path").toString();
if(path.contains("Scripts")){
String fileName = path.replace(scriptsDirectoryReplace, "");
downloadFromGithub(scriptsRepositoryDirectory+fileName,fileName);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String getResponseBody(HttpURLConnection conn) {
BufferedReader br = null;
StringBuilder body = null;
String line = "";
try {
br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
body = new StringBuilder();
while ((line = br.readLine()) != null)
body.append(line);
return body.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int saveFile(HttpURLConnection connection, String fileName) throws IOException {
// opens input stream from the HTTP connection
String saveFilePath = fileSaveDirectory + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream writer = new FileOutputStream(saveFilePath);
InputStream reader = connection.getInputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
reader.close();
writer.close();
return connection.getResponseCode();
}

HTTPUtils deprecated .. what do I do instead?

I need to download icons from the OpenWeatherMap website, build a URL, download the image, save it to local storage and also check to see if they already exist. HTTPUtils is underlined in red and when I looked it up, it's no longer being used. The Bitmap code was given to use by the professor.
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(TEMPS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//this is what talks to the xml on the website
xpp.setInput(inputStream, "UTF-8");
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("temperature")) {
curr = xpp.getAttributeValue(null, "value");
//tell android to call onProgressUpdate with 25 as parameter
publishProgress(25);
min = xpp.getAttributeValue(null, "min");
publishProgress(50);
max = xpp.getAttributeValue(null, "max");
publishProgress(75);
} else if (xpp.getName().equals("weather")) {
icon = xpp.getAttributeValue(null, "icon");
}
}
xpp.next();
}
//Start of JSON reading of UV factor:
//create the network connection:
URL UVurl = new URL(UV);
HttpURLConnection UVConnection = (HttpURLConnection) UVurl.openConnection();
inputStream = UVConnection.getInputStream();
//create a JSON object from the response
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
//now a JSON table:
JSONObject jObject = new JSONObject(result);
double aDouble = jObject.getDouble("value");
Log.i("UV is:", ""+ aDouble);
uv = aDouble;
//*****This is where I need help
Bitmap image = null;
URL imageUrl = new URL(IMAGE);
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
image = BitmapFactory.decodeStream(connection.getInputStream());
}
image = HTTPUtils.getImage(IMAGE);
FileOutputStream outputStream = openFileOutput(icon + ".png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
outputStream.flush();
outputStream.close();
public boolean fileExistance(String weatherIcons){
File file = getBaseContext().getFileStreamPath(weatherIcons);
return file.exists();
Log.i("File name:", ""+ file);
}
FileInputStream fis = null;
try {
fis = openFileInput("C:/Users/kathy/AndroidStudioProjects/AndroidLabs/app/src/main/res/drawable");
} catch (FileNotFoundException e) {
Log.e("Download this file", e.getMessage());
}
Bitmap bm = BitmapFactory.decodeStream(fis);
publishProgress(100);
Thread.sleep(2000); //pause for 2000 milliseconds to watch the progress bar grow
} catch (Exception ex) {
}
return null;
}
While I don't really understand which package HTTPUtils comes from, I think relying on the standard classes from the JDK and Android SDK is the way to go.
try {
// Get an open Stream to the image bytes
final InputStream stream = new URL(IMAGE).openStream();
// Wrap the Stream in a buffered one for optimization purposes
// and decode it to a Bitmap
try (final InputStream bufferedInputStream = new BufferedInputStream(stream)) {
final Bitmap image = BitmapFactory.decodeStream(bufferedInputStream);
// Process the image
}
} catch (final IOException e) {
// Handle the Exception
}
You might want to extract an helper method, which simply returns the instantiated Bitmap variable.

Using httpUrlConnection: am i setting up my connection correctly?

I am making use of the HttURLconnection and URLConnection api's to connect to a PHP file on my web host (x10host). However the connection does not seem to be established and no string data is sent.
I am sure that my PHP code is correct, so am I using the classes incorrectly in the below code?
#Override
protected String doInBackground(String... params) {
StringBuilder respData = new StringBuilder();
InputStream stream = null;
OutputStream os = null;
HttpURLConnection httpUrlConnection;
URLConnection conn;
URL url;
try {
url = new URL("my_url/recieveString.php");
conn = url.openConnection();
httpUrlConnection = (HttpURLConnection) conn;
httpUrlConnection.setUseCaches(false);
//httpUrlConnection.setRequestProperty("User-Agent", "App");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
os = httpUrlConnection.getOutputStream();
toSubmit = "test";
stream = new ByteArrayInputStream(toSubmit.getBytes(StandardCharsets.UTF_8));
copy(stream, os);
httpUrlConnection.connect();
int responseCode = httpUrlConnection.getResponseCode();
if (200 == responseCode) {
InputStream is = httpUrlConnection.getInputStream();
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is);
char[] buffer = new char[1024];
int len;
while ((len = isr.read(buffer)) != -1) {
respData.append(buffer, 0, len);
}
} finally {
if (isr != null) {
isr.close();
success = true;
}
}
is.close();
} else {
// use below to get error stream
//inputStream = httpUrlConnection.getErrorStream();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
}

Downloaded jar file corrupted

I've got this code that downloads a .jar file from a specific URL and places it into a specific folder. The jar file downloaded is a mod for a game, meaning that it has to be downloaded and run correctly without being corrupted.
The problem is, each time I try downloading the file, it ends up being corrupted in some way and causing errors when it is loaded.
This is my download code:
final static int size=1024;
public static void downloadFile(String fAddress, String localFileName, String destinationDir, String modID) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(fAddress);
outStream = new BufferedOutputStream(new
FileOutputStream(destinationDir+"/"+localFileName));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten);
System.out.println("Writing info file");
WriteInfo.createInfoFile(localFileName, modID);
}catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
outStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Any ideas what is wrong with this code?
Not sure if this will solve your problem but you should flush your buffer at the end.
outStream.flush();
your code look like quite right; try this
public static void downloadFromUrl(String srcAddress, String userAgent, String destDir, String destFileName, boolean overwrite) throws Exception
{
InputStream is = null;
FileOutputStream fos = null;
try
{
File destFile = new File(destDir, destFileName);
if(overwrite && destFile.exists())
{
boolean deleted = destFile.delete();
if (!deleted)
{
throw new Exception(String.format("d'ho, an immortal file %s", destFile.getAbsolutePath()));
}
}
URL url = new URL(srcAddress);
URLConnection urlConnection = url.openConnection();
if(userAgent != null)
{
urlConnection.setRequestProperty("User-Agent", userAgent);
}
is = urlConnection.getInputStream();
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int len, totBytes = 0;
while((len = is.read(buffer)) > 0)
{
totBytes += len;
fos.write(buffer, 0, len);
}
System.out.println("Downloaded successfully");
System.out.println(String.format("File name: %s - No of bytes: %,d", destFile.getAbsolutePath(), totBytes));
}
finally
{
try
{
if(is != null) is.close();
}
finally
{
if(fos != null) fos.close();
}
}
}

Parsing Binary Data from HttpServletRequest

What is the general approach to retrieve binary data that is posted to a Java Servlet? A byte[] is being posted to this servlet and I think I have to somehow parse the HttpServletRequest.getInputStream() and pull out the byte[] contents. Any ideas on how to change the below code to accomplish this?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
String body = stringBuilder.toString();
System.out.println(body);
}
Don't wrap your inputstream in any "Reader"s, as they convert from bytes to characters, and you want the bytes.
yes. ditch all the Readers and use the InputStream you were handed on the 3rd line. if you don't understand the relationship between byte[] and InputStream, i would suggest reading the API docs and some good java tutorials.

Categories