Example of POST request in Android studio - java

I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:
Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
", Name: " + json_data.getString("Name") +
", Years: " + json_data.getString("Age") +
", Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+", Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content", data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards

Use HttpURLConnection, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permission android:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
new ReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class ReceiveData extends AsyncTask<URL, Integer, Long> {
String response = "";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder feedback = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
public void getData() throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnection client = null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a
// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStream os = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
#Override
protected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloaded
final byte[] result = response.getBytes();
Long numOfBytes = Long.valueOf(result.length);
return numOfBytes;
}
protected void onPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.
InputCode input = new InputCode();
input.passToDisplay(myContext, response);
}
}

Use Volley as defined here. It's far more easier.

Related

can't create a file from a android helper class

I'm trying to create a file in a JSONhelper class, that is not an activity.
From what I've read, I can't use the method openFileOutput(String name, Context.MODE_PRIVATE).
I guess that only works when you're creating a file from an activity. But I can't seem to find out how to create a file from a helper class. Here is my class and what I'm trying to accomplish is pretty straight forward.
Please help and thanks in advance.
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.checkinsystems.ez_score.model.Match;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
import static java.security.AccessController.getContext;
public class JSONhelper {
private static final String FILE_NAME = "new_match.json";
private static final String TAG = "JSONHelper";
public static boolean exportToJSON(Context context, List<Match> matches) {
Matches newMatch = new Matches();
newMatch.setMatches(matches);
Gson gson = new Gson();
String jsonString = gson.toJson(newMatch);
Log.i(TAG, "exportToJSON: " + jsonString);
FileOutputStream fileOutputStream = null;
File file = new File(FILE_NAME);
try {
fileOutputStream = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fileOutputStream.write(jsonString.getBytes());
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static List<Match> importFromJSON(Context context) {
FileReader reader = null;
try {
File file = new File(FILE_NAME);
reader = new FileReader(file);
Gson gson = new Gson();
Matches matches = gson.fromJson(reader, Matches.class);
return matches.getMatches();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
static class Matches {
List<Match> matches;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
}
To do that you need a context object which you can get by doing the following:
Set the name attribute for your <application> in the manifest file:
<application android:name="com.companyname.applicationname">....</application>
Create the class applicationname which extends Application:
public class applicationname extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
applicationname.context = getApplicationContext();
}
public static Context getAppContext() {
return applicationname.context;
}
}
Call getAppContext() within your helper class to get the context and use it to call openFileOutput:
FileOutputStream fos = getAppContext().openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
Use this JSON Helper Class
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class JSONHelper extends AsyncTask<Void, Void, String> {
Context context;
String myUrl;
ProgressDialog progressDialog;
OnAsyncLoader onAsyncLoader;
HashMap<String, String> hashMap;
JSONObject hashMapWithJson;
boolean isProgressVisible;
public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible) {
this.context = context;
myUrl = url;
this.onAsyncLoader = onAsynckLoader;
this.hashMap = hashMap;
this.isProgressVisible = isProgressVisible;
}
public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible, JSONObject jsonObj) {
this.context = context;
myUrl = url;
this.onAsyncLoader = onAsynckLoader;
this.hashMap = hashMap;
this.isProgressVisible = isProgressVisible;
this.hashMapWithJson = jsonObj;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isProgressVisible) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait a moment");
progressDialog.show();
}
}
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
URL url = new URL(myUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
if (hashMap != null) {
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(hashMap));
writer.flush();
writer.close();
os.close();
}
if (hashMapWithJson != null) {
httpURLConnection.setReadTimeout(20000);
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(hashMapWithJson.toString());
/*OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(hashMapWithJson.toString());*/
// writer.write(getPostDataString(hashMap));
wr.flush();
wr.close();
// os.close();
}
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
}
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
Log.e("result", "Error = " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("result", "Error = " + e.toString());
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (isProgressVisible) {
progressDialog.dismiss();
}
try {
onAsyncLoader.OnResult(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
Log.d("url", result.toString());
return result.toString();
}
}

Issue in getting authentication URL in google drive V2

I'm working with google drive authentication using OAuth2.0. Its working fine. As soon as the user clicks authenticate it opens a new tab in a browser for user permission. I'm not able to get the Url which it opens in new tab. I want to access my web application remotely. It doesn't work because the validation window opens in a default browser where application is running. Is there any way to get the complete Url?
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class GoolgeDriveUpload3 {
private static String CLIENT_ID = "xxxxxxxxxx";
private static String CLIENT_SECRET = "yyyyyyyyyy";
static HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static JsonFactory jsonFactory = new JacksonFactory();
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/drive-java-quickstart");
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws IOException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, jsonFactory,
CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE_FILE)).setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline").setApprovalPrompt("auto").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalCallbackServer()).authorize("user");
Drive service = new Drive.Builder(HTTP_TRANSPORT, jsonFactory, credential).build();
List<File> result = new ArrayList<File>();
Files.List request = null;
request = service.files().list();
FileList files = request.setQ("'root' in parents and trashed=false ").execute();
result.addAll(files.getItems());
request.setPageToken(files.getNextPageToken());
for (File f : result) {
System.out.println("Files are: " + f.getTitle() + " " + f.getId() + " " + f.getAlternateLink());
}
}
}
import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LocalCallbackServer implements VerificationCodeReceiver {
volatile String code;
private final int LOCAL_SERVER_PORT = 9058;
#Override
public synchronized String waitForCode() {
try {
this.wait();
} catch (Exception ex) {
}
System.out.println("returning code is -> " + code);
return code;
}
#Override
public String getRedirectUri() {
new Thread(new MyThread()).start();
return "http://127.0.0.1:" + LOCAL_SERVER_PORT;
}
#Override
public void stop() {
}
class MyThread implements Runnable {
#Override
public void run() {
try {
// return GoogleOAuthConstants.OOB_REDIRECT_URI;
ServerSocket ss = new ServerSocket(LOCAL_SERVER_PORT);
System.out.println("server is ready...");
Socket socket = ss.accept();
System.out.println("new request....");
InputStream is = socket.getInputStream();
StringWriter writer = new StringWriter();
String firstLine = null;
InputStreamReader isr = new InputStreamReader(is);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
firstLine = read;
OutputStream os = socket.getOutputStream();
PrintWriter out = new PrintWriter(os, true);
StringTokenizer st = new StringTokenizer(firstLine, " ");
st.nextToken();
String codeLine = st.nextToken();
st = new StringTokenizer(codeLine, "=");
st.nextToken();
code = st.nextToken();
out.write("RETURNED CODE IS " + code + "");
out.flush();
// is.close();
socket.close();
System.out.println("Extracted coded is " + code);
synchronized (LocalCallbackServer.this) {
LocalCallbackServer.this.notify();
}
System.out.println("return is " + sb.toString());
} catch (IOException ex) {
Logger.getLogger(LocalCallbackServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

Call static String onCreate from other Class

How can I call "getContent" inside "onCreate"?
I am getting errors like
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity: android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
main.java
protected void onCreate(Bundle savedInstanceState) {
Log.d("URL", HttpUtils.getContents("http://google.com"));
}
HttpUtils.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtils {
public static String getContents(String url) {
String contents ="";
try {
URLConnection conn = new URL(url).openConnection();
InputStream in = conn.getInputStream();
contents = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.v("MALFORMED URL EXCEPTION");
} catch (IOException e) {
Log.e(e.getMessage(), e);
}
return contents;
}
private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
In android you cann't perform any networking task on UI thread. so you will have perform Networking task on a Different thread. For this you can use normal java Threads but this is not a good approach in android. you should use Async Task.
You can follow any good tutorial on google.

wait for php script then download

i have a php script which creates a file if it not exists. the php script sends the file after it created it. now i have the problem that my download class can't download it (i don't know exactly why) when the php file is creating a new file. but if the php script sends a cached file the download works.
Is there any way to let the android wait until the php script is done executing?
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Looper;
import android.provider.ContactsContract.Directory;
import android.util.Log;
public class DownloadMP3 extends AsyncTask<String, Integer, String> {
private OnTaskRunning listener;
public DownloadMP3(OnTaskRunning listener){
this.listener=listener;
}
#Override
protected String doInBackground(String... url) {
int count;
try {
Log.d("Info", "create file");
Download down = new Download();
JSONObject jObject = new JSONObject(down.JSON(conf.d + "convert.php?v=" + url[0]));
Log.d("Info","json file: " + jObject.get("fle"));
URL u = new URL(conf.d + "convert.php?v=" + jObject.get("fle"));
Log.d("Info", "dl u");
URLConnection conexion = u.openConnection();
Log.d("Info", "dl op");
conexion.connect();
Log.d("Info", "dl co");
File directory = new File(Environment.getExternalStorageDirectory() + "/Music/VBT Splash/");
Log.d("Info", "dl di");
if (!directory.exists() || !directory.isDirectory()){
directory.mkdirs();
}
InputStream input = new BufferedInputStream(u.openStream());
String filename = conexion.getHeaderField("Content-Disposition");
String file = filename.substring(filename.indexOf("\"")+1, filename.lastIndexOf("\""));
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Music/VBT Splash/" + file);
int lenghtOfFile = conexion.getContentLength();
byte data[] = new byte[4096];
long total = 0;
listener.onTaskStarted();
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
publishProgress((int) (total * 100 / lenghtOfFile));
}
Log.d("Info", "dl done");
listener.onTaskDone();
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
listener.onTaskProgress(progress[0]);
}
protected void onPostExecute(int result) {
}
}
You must convey a re-direct to your client code. If you just hit the full file path url , and it doesn't exists, it won't be downloaded. So instead, first get download url from script. ( a new one will be created if it doesn't exists) then, download that url. That makes a total of 2 requests to server.

Cannot upload a file from Android to PHP server

I am making an application which uploads a file from a SD card to PHP server. Howeverm when I try to do this, I'm getting an error.
My Android code is as below:
package de.fileupload;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import android.os.Bundle;
#SuppressWarnings("unused")
public class FileUpload extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView tmp = (TextView) findViewById(R.id.textView1);
tmp.setText("Hi! Click the button!");
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
File f = new File("mnt/sdcard/SMSBackup.txt");
try {
f.createNewFile();
Date d = new Date();
PrintWriter writer = new PrintWriter(f);
writer.println(d.toString());
writer.close();
HttpClient client = new DefaultHttpClient();
httpPostFileUpload(client, "mnt/sdcard/SMSBackup.txt", "http://10.0.2.2:8080/admin/admin/upload1.php", "uploadedfile");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void httpPostFileUpload(
HttpClient client,
String filePath,
String uploadUri,
String inputNameAttr) throws ClientProtocolException,
IOException {
HttpUriRequest request = new HttpPost(uploadUri);
MultipartEntity form = new MultipartEntity();
client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
form.addPart(inputNameAttr, new FileBody(new File(filePath)));
((HttpEntityEnclosingRequestBase) request).setEntity(form);
try {
client.execute(request);
} catch (ClientProtocolException e) {
throw e;
} catch (IOException ee) {
throw ee;
}
}
}
and my PHP files are as below:
upload1.php
<meta name="generator" content="Namo WebEditor(Trial)">
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br /><input
type="submit" value="Upload File" />
</form>
<?php
$to_file = "tmp/" . basename($_FILES['uploadedfile']['name']);
$from_file = $_FILES['uploadedfile']['tmp_name'];
if (move_uploaded_file($from_file, $to_file)) {
echo "Successful upload";
?>
<?php echo $to_file;?>
<?php
} else {
echo "Unsuccessful upload";
}
?>
and upload.php is:
<?php
// Where the file is going to be placed
$target_path = "localhost/admin/admin/uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$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";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
Can any one please tell that where i m wrong? It always shows the unsuccessful upload for the file. While my server is running.
Try to use instead move_uploaded_file(), function copy(). They use the same input parameters, like this:
if(copy($_FILES['uploadedfile']['tmp_name'], $target_path)) { ...
Most likely the PHP process has no permissions to move the uploaded file to different folder after successful upload, because the moving contains in essence copy and delete operation.
One more thing - try not to change the permission of the uploaded file to 0644, because this also can be restricted to the PHP process, i.e. when you deal with file system operations on Linux (I assume you use Linux machine for your server) the working process (in your case PHP and apache) has particular permissions set and maybe they do not have ability to delete/move files outside their working folder.
You should also change the uploading folder permission to 755 or 777.
This class allow you to upload file directly. No need to decode your file.
public class Helpher extends AsyncTask<String, Void, String> {
Context context;
JSONObject json;
ProgressDialog dialog;
int serverResponseCode = 0;
DataOutputStream dos = null;
FileInputStream fis = null;
BufferedReader br = null;
public Helpher(Context context) {
this.context = context;
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Main2Activity.this, "ProgressDialog", "Wait!");
}
#Override
protected String doInBackground(String... arg0) {
try {
File f = new File(arg0[0]);
URL url = new URL("http://localhost:8888/imageupload.php");
int bytesRead;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String contentDisposition = "Content-Disposition: form-data; name=\"keyValueForFile\"; filename=\""
+ f.getName() + "\"";
String contentType = "Content-Type: application/octet-stream";
dos = new DataOutputStream(conn.getOutputStream());
fis = new FileInputStream(f);
dos.writeBytes(SPACER + BOUNDARY + NEW_LINE);
dos.writeBytes(contentDisposition + NEW_LINE);
dos.writeBytes(contentType + NEW_LINE);
dos.writeBytes(NEW_LINE);
byte[] buffer = new byte[MAX_BUFFER_SIZE];
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.writeBytes(NEW_LINE);
dos.writeBytes(SPACER + BOUNDARY + SPACER);
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
Log.w(TAG,
responseCode + " Error: " + conn.getResponseMessage());
return null;
}
br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.d(TAG, "Sucessfully uploaded " + f.getName());
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
dos.close();
if (fis != null)
fis.close();
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return String.valueOf(serverResponseCode);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
}
This is the AsyncTask "Helpher" class used for upload image from Android. To call this class use like syntax below.
new Main2Activity.Helpher(this).execute(fileUri.getPath());
Here fileUri.getPath() local image location. If you want to see the server response value is avilable in " StringBuilder sb" you can print sb value

Categories

Resources