Uploading Files using PHP Script to Web Hosting - java

I have written out a program which is designed to upload text files created from motion data information to a PHP cloud server that I have set up with 000webhost.com. Ive tried running it however it will not run for some reason. None of the sensor information is uploaded and there seems to be a problem me thinks on the server end. Is the error in the script or code? (or both?).
Edit: Yeah I know its not "great", I am still fairly new to coding and been trying to fiddle around with the code for a while (still working on it).
Program
package com.example.motionsense3;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimerTask;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.io.File;
import android.util.Log;
public class SaveTimer extends TimerTask
{
String upLoadServerUri = null;
final String uploadFilePath = "/data/data/com.example.motionsense3/";
//final String uploadFileName = "????";
private ArrayList<String> motionData;
private ArrayList<String> motionDataClone;
private Context context;
public SaveTimer(ArrayList<String> motionData, MainActivity context) {
this.motionDataClone = (ArrayList<String>) motionData.clone();
this.motionData = motionData;
this.context = context;
}
#Override
public void run() {
Log.e("DIDUPLOADWORK", Boolean.toString(upload()));
}
private void save() {
try {
this.motionDataClone = (ArrayList<String>) motionData.clone();
motionData.clear();
FileOutputStream fileOutput = context.openFileOutput("scaninfo_" + new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(new Date()).toString(), context.MODE_WORLD_READABLE);//.write(s);
for(String s : motionDataClone)
{
fileOutput.write(s.getBytes());
}
fileOutput.close();
} catch (Exception e) {
}
//save();
}
public boolean upload(){//ArrayList<String> motion){//String sourceFileUri) {
/************* Php script path ****************/
upLoadServerUri = "motionsense.uphero.com/public_html/motiondata/UploadToServer.php";
//String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
URL url = new URL(upLoadServerUri);
String fileName = "scaninfo_" + new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(new Date()).toString();
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file; filename="
+ fileName + "" + lineEnd);
dos.writeBytes(lineEnd);
for(String s : motionDataClone)
{
dos.write(s.getBytes());
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.e("SERVERRESPONSE", serverResponseMessage);
Log.e("SERVERRESPONSECODE", String.valueOf(serverResponseCode));
}
catch(Exception e){return false;}
return true;
}
}
Php script
<?php
$file_path = "motiondata/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>

Just quickly glancing through the code, I believe your problem is here:
upLoadServerUri = "motionsense.uphero.com/public_html/motiondata/UploadToServer.php";
Basically you're trying to make a connection to UploadToServer.php through this public_html directory, however, this directory doesn't exist publically (it's where your "root" files are served from when accessing a website with '/'). Change to:
upLoadServerUri = "motionsense.uphero.com/motiondata/UploadToServer.php";
And you should be fine (assuming everything else works haha).

Related

WebAPI POST in Java with file in body

I have a problem calling a webAPI in Java. Basically, I have to upload a file (xml or pdf) but I cannot get it work. I tried in Postman and it works, I had to put in the body the filename and the content of the file
If I declare the filedata as file (see pic. 3) it works. I tried to do it in Java but I cannot find a way to do it. I tried many snippets from the web buut at best when I run them I get error 500.
The code I got so far is
package api_post;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class API_POST {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String charset = "UTF-8";
File uploadFile1 = new File("[fileWithPath]");
String requestURL = "";
requestURL = "[URL]";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFormField("username", "[user]");
multipart.addFormField("password", "[pwd]");
multipart.addFormField("owner", "[owner]");
multipart.addFormField("destination", "[destination]");
multipart.addFilePart("fileData", uploadFile1);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
public static class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public MultipartUtility(String requestURL, String charset) throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
System.out.println("Entrato");
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}}}
Can anybody help me please?
I just discovered that in postman I can see the java source code of the call. I used that and now it works.

Unable to upload mp3 file from Android app to asp.net backend

I want to upload mp3 file from Android app to my asp.net server, I am using this class on client side
import android.util.Log;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
String iFileName = "temp.mp3";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Then I using the above class like that
public void uploadFile(){
try {
File appDir = getContext().getExternalFilesDirs(null)[0];
File file = new File(appDir.getAbsolutePath() + "/Audios");
if (!file.exists()) {
file.mkdirs();
}
fileName = appDir.getAbsolutePath() + "/Audios/temp.mp3";
FileInputStream fstrm = new FileInputStream(fileName);
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.example.com/Fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
And this is the server side asp.net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Fileup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
string vTitle = "";
string vDesc = "";
string FilePath = Server.MapPath("~/files/cur_file.mp3");
if (!string.IsNullOrEmpty(Request.Form["title"]))
{
vTitle = Request.Form["title"];
}
if (!string.IsNullOrEmpty(Request.Form["description"]))
{
vDesc = Request.Form["description"];
}
HttpFileCollection MyFileCollection = Request.Files;
if (MyFileCollection.Count > 0)
{
// Save the File
MyFileCollection[0].SaveAs(FilePath);
}
}
}
Notes:
I added INTERNET & EXTERNAL STORAGE permission to my client app
The client side reaches to this line and return code 500 Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode())); and then throw exception in the next line InputStream is = conn.getInputStream();
Then I can't find the mp3 file in "files" folder on my Server
The mp3 file just 16 kb
What is the problem?
I solved it, There was no permission to write files for the folder "files", Thanks

I have an incoming HttpServletRequest that contains a request part that I need to pass into a new httpUrlConnection

Let me see if I can explain this. The front-end provides me with a spreadsheet that I need to pass to my central server via an api call to do the processing. I use the following code to pull out the spreadsheet and create my work book,
Part spreadsheet = request.getPart(SPREADSHEET);
Workbook workbook = WorkbookFactory.create(spreadsheet.getInputStream());
Where 'request' is an incoming HttpServletRequest object. I know that it works and I can manipulate the spreadsheet, but I need to pass it along to my other server to do the processing and I can't figure out how to do that. Here is what I have so far.
#Path("/uploadSpreadsheet")
#POST
public String uploadSpreadsheet(#Context final HttpServletRequest request,#Context final HttpHeaders httpHeaders) throws IOException, ServletException, InvalidFormatException, JSONException {
return uploadUtil(request, "rest/memberService/uploadSpreadsheet");
}
Here is the util that I can't get right.
private String uploadUtil(HttpServletRequest request, String serviceUrl) throws MalformedURLException, ProtocolException, IOException, ServletException {
String baseUrl = "http://localhost:8084/centralservices/";
String urlString = baseUrl.concat(serviceUrl);
URL url = new URL(urlString);
String boundary = "===" + System.currentTimeMillis() + "===";
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpCon.setRequestProperty("Key", "SOMEKEYHERE");
httpCon.setRequestProperty("clientAddress", request.getRemoteAddr());
//I know this is wrong but I'm not sure what goes here:
httpCon.setRequestProperty("file", request.getPart(SPREADSHEET));
int responseCode;
StringBuilder resp = new StringBuilder();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null) {
resp.append(inputLine);
}
} finally {
if (in != null) {
in.close();
}
httpCon.disconnect();
}
return resp.toString();
}
Hopefully that makes sense. I mean all I really need to do is transfer the request identically(with all the formparts and everything) to a different url. Once it gets there I have no issue processing it. Let me know if I am unclear on something. I'm pretty new to this stuff. We already have a rest utility that I've always used for everything else, but it doesn't work for this scenario so I need to create a new one.
If you are using the Servlet-Api 3.0, then the below approach gives you on how to read the stream and write back the stream to the subsequent URL.
http://balusc.omnifaces.org/2009/12/uploading-files-in-servlet-30.html
From your code above , once you get the Part , convert the obtained file/workbook to bytebuffer and then write it to Output stream.
connection.getOutputStream().write(filebuff);
Because adding to request property will not help in this case.
Thanks
Maruthi
I was too unfamiliar with some of the options presented so I just converted the spreadsheet into a json string and sent that over with my existing rest utility.
I think there's a lot of stuff missing in the multipart request. See this link
Sending files using POST with HttpURLConnection.
Also it's probably better to use some API to do this for you, probably easiest would be apache httpclient
See the example usage in this SO post
If you do need to use URLConnection for this then you can use this multipart utility from codejava.net
I'm posting the code from there here for backup in case original link goes down.
MultipartUtility
package net.codejava.networking;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* This utility class provides an abstraction layer for sending multipart HTTP
* POST requests to a web server.
* #author www.codejava.net
*
*/
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
/*Following line has no significance for the task this utility performs*/
/*httpConn.setRequestProperty("Test", "Bonjour");*/
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
Test Program
package net.codejava.networking;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* This program demonstrates a usage of the MultipartUtility class.
* #author www.codejava.net
*
*/
public class MultipartFileUploader {
public static void main(String[] args) {
String charset = "UTF-8";
File uploadFile1 = new File("e:/Test/PIC1.JPG");
File uploadFile2 = new File("e:/Test/PIC2.JPG");
String requestURL = "http://localhost:8080/FileUploadSpringMVC/uploadFile.do";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addHeaderField("User-Agent", "CodeJava");
multipart.addHeaderField("Test-Header", "Header-Value");
multipart.addFormField("description", "Cool Pictures");
multipart.addFormField("keywords", "Java,upload,Spring");
multipart.addFilePart("fileUpload", uploadFile1);
multipart.addFilePart("fileUpload", uploadFile2);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}

I tried c2dm and i need server side

I have problem with : Google server said: 401, Unauthorized
I worked on the tomcat server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import com.liferay.portal.kernel.exception.SystemException;
import fr.intuitiv.dal.model.SmartPhone;
import fr.intuitiv.dal.service.SmartPhoneLocalServiceUtil;
public class URLCaller {
public static void callGoogle() throws IOException, SystemException {
URL url = new URL("https://android.clients.google.com/c2dm/send");
StringBuilder builder = new StringBuilder();
byte[] postData = null;
HttpsURLConnection conn = null;
String authorized_Key = getAuthorization();
// For each smartPhone
for(SmartPhone smartPhone : SmartPhoneLocalServiceUtil.getSmartPhones(0, SmartPhoneLocalServiceUtil.getSmartPhonesCount())) {
//Setup data
builder.append("registration_id=" + smartPhone.getRegistrationId());
builder.append("&collapse_key=").append("0");
builder.append("&data.payload=").append("The test work, drink a beer");
postData = builder.toString().getBytes("UTF-8");
//Calling server
conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new CustomizedHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content_Lenght", Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authorized_Key);
// Issue the HTTP POST request
System.out.println("" + conn.getOutputStream());
OutputStream out = conn.getOutputStream();
out.write(postData);
out.flush();
System.out.println("Google server said: " + conn.getResponseCode() + ", " + conn.getResponseMessage());
out.close();
}
}
public static String getAuthorization() throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(user.config.EMAIL);
builder.append("&Passwd=").append(user.config.PASSWORD);
builder.append("&accountType=GOOGLE");
builder.append("&source=Google-C2DM-Example");
builder.append("&service=ac2dm");// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = conn.getOutputStream();
output.write(data);
output.flush();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
output.close();
return clientAuthToken;
}
private static class CustomizedHostnameVerifier implements HostnameVerifier {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
I get getAuthorization() i have a huge key.
I have my regId from the phone, i send it to the server when i get new one.
I have Android Market and i am log in.
I have registration to the google c2dm.
Are you sure, that this
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String[] split = reader.readLine().split("=");
// Finally get the authentication token
String clientAuthToken = split[1];
// To something useful with it
gives you the part after "Auth="?
Also you should trim the authToken because there might be a \n at the end that messes up the header:
conn.setRequestProperty("Authorization", "GoogleLogin auth=" + StringUtils.trim(authorized_Key));

Upload a picture from Android to PHP server

I am trying to upload file to a php server from my android device. There is thread with same question but he is using a different method. My Android side code works fine and shows no error message but server is not receiving any file. here is my sample code, I found it online.
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class uploadfile extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
doFileUpload();
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/def.jpg";
// Is this the place are you doing something wrong.
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.168.1.6/index.php";
try
{
//------------------ CLIENT REQUEST
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
}
and my php server side code is as follows
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
}
else{
echo "There was an error uploading the file, please try again!";
}
?>
Apache is running. When i run server, this error msg appears There was an error uploading the file, please try again!. I have checked the log data in eclipse and what i think is the socket problem but i am not sure. Please help if anyone knows the solution.
11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
It seems that the server is not responding to the client. Try uploading using an ftp connection through the Android application, if that works then check your Apache configuration on accepting connections and the writable directories. When I had a similar problem it turned out that my directory gave no write privileges.
Is the error from Java or from Apache?
Change your code in the following way for the correct escape sequences:
Replace
String lineEnd = "rn";
with
String lineEnd = "\r\n";

Categories