Android Json HTTP Post, Unable to parse data - java

Sorry to trouble you, as I am new to Android programming, and i have face the following problem while trying retrieve my send and receive a response from my local host server.
The program seem to auto close when i try to launch it at first. But after implementing
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The program is able to run, however, the data is not parse across.
I have allowed the Internet permission in my android Manifest script.
My Android Codes
package kx.practice;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.TextView;
public class JsonHttpPractice2Activity extends Activity {
TextView tv;
String text;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tv = (TextView)findViewById(R.id.textView1);
text = "";
try {
postData();
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("Error in JSON Exception 1");
e.printStackTrace();
}
}
public void postData() throws JSONException{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/phpWebservice/AndroidTest.php");
JSONObject json = new JSONObject();
try {
// JSON data:
json.put("name", "Fahmi Rahman");
json.put("position", "sysdev");
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
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();
}
}
text = sb.toString();
System.out.println("This is my text" +text);
}
tv.setText(text);
}catch (ClientProtocolException e) {
System.out.println("Error in JSON Exception 2");
// TODO Auto-generated catch block
} catch (IOException e) {
System.out.println("Error in JSON Exception 3");
// TODO Auto-generated catch block
}
}
}
And lastly, my PHP codes
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";
$name = $data->name;
$pos = $data->position;
echo "Result: \n";
echo "--------------\n";
echo "Name : ".$name."\n Position : ".$pos;
?>
By the way, I got these codes from an online website. However, if these codes are able to work, i should be able to implement it into my project.

You are trying to access the network on the main thread. This is a very bad idea. You need to do the network access in a separate thread instead. The linked article provides several guidelines for doing this.
If you still have problems after moving the network access to a different thread, then feel free to come back and ask more questions.
(The reason your app was killed is because the Android system noticed it hadn't responded for a while, since it was waiting for network traffic.)

Related

Can I import an image from any type of website?

I'm trying to import images from Internet using Java (IDE IntelliJ) but I don't know how to select an image (in this case the first of the row) from google images.
For example I tried to search the capital of Rome and Napoli, but the code can't find any image from images google's section.
Probably you don't understand much what I said, so below you will find the code I wrote with the relative error
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main{
public static void main(String[] args) {
String[] listaCapitali = {
"Roma",
"Napoli",
};
for (String capitale : listaCapitali) {
ricercaGoogle("https://www.google.com/search?q=" + capitale + "+cartina&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj-moK1y-D0AhXIzaQKHeXUBLUQ_AUoAXoECAEQAw&cshid=1639392166213289&biw=2240&bih=1082&dpr=2");
}
}
private static void ricercaGoogle(String urlPath) {
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int response = connection.getResponseCode();
System.out.println(response);
BufferedImage image = ImageIO.read(url);
FileOutputStream fos = new FileOutputStream(String.valueOf(image));
fos.write(response);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The error says:
403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)
403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)
Could you also help me to download those images on my computer named with the capital name? Thanks a lot
First thing to do :Your URL is not an URL of an Image ! try to change the URL
You can inspire from that code it works fine :
Get an image from a HTTPGET and Put it on a file
new Thread(new Runnable() {
#Override
public void run() {
HttpClient httpclient = HttpClients.createDefault();
/*
* put your urlPath here instead of http://localhost...
*/
HttpGet httpget = new HttpGet("http://localhost:9090/imageFilm/1");
// Execute and get the response.
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// receiving an image and write it within a file
try (FileOutputStream outputStream = new FileOutputStream(
/*
* here i create a file with the image received from the httpGet , you can do other things
*/
new File("C:\\Users\\OUSSAMA\\Desktop\\xc.png"), false)) {
int read;
byte[] bytes = new byte[1024];
while ((read = instream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
} catch (UnsupportedOperationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
Apache HttpClient dependency needed :
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.13
All The code in one class :
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
public class Main{
public static void main(String[] args) {
String[] listaCapitali = {
"Roma",
"Napoli",
};
for (String capitale : listaCapitali) {
//ricercaGoogle("https://www.google.com/search?q=" + capitale + "+cartina&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj-moK1y-D0AhXIzaQKHeXUBLUQ_AUoAXoECAEQAw&cshid=1639392166213289&biw=2240&bih=1082&dpr=2");//Your URL is not an URL of an Image ; you must change it !
ricercaGoogle("https://i.pinimg.com/originals/1b/75/84/1b758419a811ae05ad4da61acdb7ce22.jpg");
}
}
private static void ricercaGoogle(String urlPath) {
HttpClient httpclient = HttpClients.createDefault();
/*
* put your urlPath here instead of http://localhost...
*/
HttpGet httpget = new HttpGet(urlPath);
// Execute and get the response.
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// receiving an image and write it within a file
try (FileOutputStream outputStream = new FileOutputStream(
/*
* here i create a file with the image received from the httpGet , you can do other things
*/
new File("C:\\Users\\Mourad\\Desktop\\xc.png"), false)) {
int read;
byte[] bytes = new byte[1024];
while ((read = instream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
} catch (UnsupportedOperationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

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.

Example of POST request in Android studio

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.

Android tcp socket can not receive data

I am trying to work with sockets in android programming, sending to the server works fine but i have problems with receiving a string from the server.
the socket is connected, but if the server is sending a string the android app only prints out: java.io.BufferedReader#418daee0
i dont know what that mean..is it an error or something like that?
this is my code:
Maybe someone could help me a little bit to get that work.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 2000;
private static final String SERVER_IP = "192.168.1.1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String test = br.toString();
TextView message = (TextView) findViewById(R.id.received);
message.setText(test);
//in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
what you need to do is read from the BufferedReader. Currently you are just printing the br object.
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine ()) != null) {
System.out.println (line);
}
as per the javadocs readLine will return null if the end of the stream has been reached
problem:
String test = br.toString();
You are basically referencing the memory location in string form of the br object thus printing the memory location in your TextView. What you need to do is to read the inputStream from the socket connection of the server from your BufferedReader object.
solution:
String test = br.readLine();
The readLine method will wait for the response of the server from the InputStream where the socket is connected. Now the above will only get one line of response from the server if the server sends multiple line then you put it in a while loop.

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