Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9063771
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T16:05:25+00:00 2026-06-16T16:05:25+00:00

I want to send image data from android client to the server. But there

  • 0

I want to send image data from android client to the server. But there is a problem, there are times when I send data the received message successfully, but there are times when I send but not receive anything, even though the server has received the data.

function upload

 public void upload()
{
    try
    {
        // nén hình lại và gửi lên server
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        alteredBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);

        // chyển hình ảnh về dạng byte
        byte[] ba = bao.toByteArray();

        // dùng thư viện Base64 chuyển mảng Byte về chuỗi String
        String ba1 = Base64.encodeBytes(ba);

        // Đường dẫn đến server
        String sampleURL = SERVICE_URL + "/uploadimage.php";

        // Tạo mới một lớp CallUrl
        CallUrl wst = new CallUrl(CallUrl.POST_TASK, this, "Uploading data...", 2, "");

        // Thêm data
        wst.addNameValuePair("image", ba1);
        wst.addNameValuePair("mahoadon", mahoadon);

        // Gửi lên server
        wst.execute(new String[] {
                sampleURL
        });
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

Class Callurl with flag=2

public class CallUrl extends AsyncTask<String, Integer, String> {

public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// thời gian chờ của một kết nối, tính theo milliseconds (waiting to
// connect)
private static final int CONN_TIMEOUT = 3000;
// thời gian chờ của một socket, tính bằng milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private int flag = 0;
private String ID;
private ProgressDialog progressDialog;

// Khởi tạo
public CallUrl(int taskType, Context mContext, String processMessage, int flag, String ID) {

    this.taskType = taskType;
    this.mContext = mContext;
    this.processMessage = processMessage;
    this.flag = flag;
    this.ID = ID;
}

@Override
protected void onPostExecute(String response) {

    progressDialog.dismiss();
    // Khai báo các thành phần cần thiết
    TextView txtusername = (TextView) ((Activity) mContext).findViewById(R.id.loginUsername);
    TextView txtpassword = (TextView) ((Activity) mContext).findViewById(R.id.loginPassword);
    CheckBox checkBox = (CheckBox) ((Activity) mContext).findViewById(R.id.checkBox1);
    DB_Adapter mDb = new DB_Adapter(mContext);
    final ArrayList<String> phonenumberArray = new ArrayList<String>();
    final ArrayList<String> codeInvoiceArray = new ArrayList<String>();
    final ArrayList<String> nameArray = new ArrayList<String>();
    final ArrayList<String> addressArray = new ArrayList<String>();
    final ArrayList<String> urlArray = new ArrayList<String>();

    // Nếu flag=0 tương đương với việc lấy thông tin đăng nhập từ server
    if (flag == 0)
    {
        try
        {
            // Dùng Json đọc thông tin nhận được từ server
            JSONObject json_data = new JSONObject(response);
            String result = json_data.getString("result");

            // Nếu kết quả trả về là đúng sẽ hiển thị activity invoice
            if (result.equalsIgnoreCase("User Found"))
            {

                Toast.makeText(mContext, "Đăng nhập thành công",
                        Toast.LENGTH_SHORT).show();

                // đăng nhập thành công sẽ chuyển vào activity Invoice
                Intent j = new Intent(mContext, Invoice.class);
                j.putExtra("ID", txtusername.getText().toString());
                mContext.startActivity(j);
                checkBox.setChecked(false);
            }

            // Nếu sai sẽ yêu cầu nhập lại
            else
            {
                String mess = "Tên đăng nhập hoặc mật khẩu không đúng!Làm ơn nhập lại!";
                Alert alert = new Alert(mContext, mess, false);
                alert.AlertDialog();
                txtpassword.setText("");
                txtusername.setText("");
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        // flag=1 lấy thông tin hóa đơn từ server
    } else if (flag == 1)
    {
        String phonenumber, name, address, url, code, status;
        JSONArray jArray;
        codeInvoiceArray.clear();
        nameArray.clear();
        phonenumberArray.clear();
        addressArray.clear();
        urlArray.clear();
        try
        {
            // kiểm tra chuỗi trả về
            // nếu rỗng thông báo hôm nay chưa có sản phẩm để giao
            // nếu có, dùng Json lấy thông tin nhận được
            if (response.equalsIgnoreCase(""))
            {
                notification("Hôm nay không còn gì để giao!");
            }
            else
            {
                JSONObject json_data = null;
                JSONObject jsonObject = new JSONObject(response);
                jArray = jsonObject.getJSONArray("Orders");
                // Mở kết nối đến database
                mDb.openDB();

                // sử dụng json lấy các giá trị thông qua các key
                // gán nó vào các mảng tương ứng
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);

                    // Lây thông tin theo mã id của người giao hàng
                    if (json_data.getString("DeliveryId").equalsIgnoreCase(ID))
                    {
                        // Lấy thông tin theo value thông qua các key
                        phonenumber = json_data.getString("PhoneNumber");
                        address = json_data.getString("Address");
                        name = json_data.getString("CustomerName");
                        url = json_data.getString("Url");
                        code = json_data.getString("CodeInvoice");
                        status = json_data.getString("Status");

                        // gán thông tin vào các mảng
                        phonenumberArray.add(phonenumber);
                        codeInvoiceArray.add(code);
                        nameArray.add(name);
                        addressArray.add(address);

                        // Gọi class load thông tin từ mảng lên listview
                        LoadListView load = new LoadListView(mContext, codeInvoiceArray,
                                nameArray, phonenumberArray, addressArray, ID);
                        load.loaddatalistview();
                        // Kiểm tra mã hóa đơn này đã có trong database chưa
                        // nếu chưa sẽ thêm data vào databse
                        // nếu đã có rồi sẽ cập nhật lại thông tin thông qua
                        // mã
                        // hóa đơn
                        if (mDb.test(code) == true)
                        {
                            mDb.insert(code, name, phonenumber, address, url, status,
                                    ID);
                            // Lưu thông tin hình ảnh hóa đơn vào sdcard
                            // save(code, url);
                            new LoadImageInvoice().execute(new String[] {
                                    url, code
                            });

                        }
                        else
                        {
                            // Nếu trùng với thông tin trong database sẽ
                            // edit lại thông tin
                            // Trong trường hợp sửa thông tin trên server
                            mDb.editAll(code, name, phonenumber, address, url, ID, status);

                        }
                    }
                }
                // Thực hiện xong, đóng kết nối
                mDb.closeDB();

            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        // Nếu flag=2 tải hình ảnh hóa đơn đã ký lên server, và thông báo
        // gửi thành công
    } else if (flag == 2)
    {
        try
        {
            // thông tin báo thành công được trả về từ server
            JSONObject json_data = new JSONObject(response);
            String result = json_data.getString("str");
            if (result.equalsIgnoreCase("success"))
            {
                // Hiển thị khi tải lên thành công
                String mess = "Tải lên server thành công!";
                Alert alert = new Alert(mContext, mess, true);
                alert.AlertDialog();
            } else if (result.equalsIgnoreCase("faill"))
            {
                // Hiển thị khi tải lên server thất bại
                String mess = "Tải lên server thất bại!";
                Alert alert = new Alert(mContext, mess, false);
                alert.AlertDialog();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

// Thông báo dạng Toast
public void notification(String mess)
{
    Toast.makeText(mContext, mess, Toast.LENGTH_SHORT).show();
}

// thêm thông tin cần thiết để gửi lên server
public void addNameValuePair(String name, String value) {

    params.add(new BasicNameValuePair(name, value));
}

// hiển thị dialog trên UI cho người dùng biết app đang trong quá trình làm
// việc
@Override
protected void onPreExecute() {

    // showProgressDialog();
    this.progressDialog = ProgressDialog.show(mContext, "",
            processMessage);
}

// kết nối đến server thông url
protected String doInBackground(String... urls) {
    String url = urls[0];
    String result = "";
    HttpResponse response = doResponse(url);
    if (response == null) {
        return result;
    } else {
        try {

            result = inputStreamToString(response.getEntity().getContent());

        } catch (IllegalStateException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);

        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }
    }
    return result;
}

// khởi tạo socket và kết nối
private HttpParams getHttpParams() {

    HttpParams htpp = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
    HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
    return htpp;
}

// thao tác xử lý khi kết nối đến server
private HttpResponse doResponse(String url) {

    HttpClient httpclient = new DefaultHttpClient(getHttpParams());
    HttpResponse response = null;

    try {
        switch (taskType) {

            //kiểm tra tác vụ cần thực hiển 
            //post gửi yêu cầu kèm thông tin
            //Get gửi yêu cầu
            case POST_TASK:
                HttpPost httppost = new HttpPost(url);
                // Add parameters
                httppost.setEntity(new UrlEncodedFormEntity(params));
                response = httpclient.execute(httppost);
                break;
            case GET_TASK:
                HttpGet httpget = new HttpGet(url);
                response = httpclient.execute(httpget);
                break;
        }
    } catch (Exception e) {

        Log.e(TAG, e.getLocalizedMessage(), e);

    }

    return response;
}

// Chuyển thông tin nhận về thành dạng chuỗi
private String inputStreamToString(InputStream is) {

    String line = "";
    StringBuilder total = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        // đọc thông tin nhận được cho đến khi kết thúc
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (IOException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }

    // Trả về giá trị chuỗi đầy đủ
    return total.toString();
}

}

error

12-26 14:36:18.539: E/WebServiceTask(9063): null
12-26 14:36:18.539: E/WebServiceTask(9063): java.net.SocketTimeoutException
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:491)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-26 14:36:18.539: E/WebServiceTask(9063):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doResponse(CallUrl.java:308)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doInBackground(CallUrl.java:265)
12-26 14:36:18.539: E/WebServiceTask(9063):     at Url.CallUrl.doInBackground(CallUrl.java:1)
12-26 14:36:18.539: E/WebServiceTask(9063):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-26 14:36:18.539: E/WebServiceTask(9063):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-26 14:36:18.539: E/WebServiceTask(9063):     at java.lang.Thread.run(Thread.java:856)
12-26 14:36:18.539: W/System.err(9063): org.json.JSONException: End of input at character 0 of 
12-26 14:36:18.539: W/System.err(9063):     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONObject.<init>(JSONObject.java:154)
12-26 14:36:18.547: W/System.err(9063):     at org.json.JSONObject.<init>(JSONObject.java:171)
12-26 14:36:18.547: W/System.err(9063):     at Url.CallUrl.onPostExecute(CallUrl.java:217)
12-26 14:36:18.547: W/System.err(9063):     at Url.CallUrl.onPostExecute(CallUrl.java:1)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask.finish(AsyncTask.java:602)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
12-26 14:36:18.547: W/System.err(9063):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
12-26 14:36:18.547: W/System.err(9063):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 14:36:18.547: W/System.err(9063):     at android.os.Looper.loop(Looper.java:137)
12-26 14:36:18.547: W/System.err(9063):     at android.app.ActivityThread.main(ActivityThread.java:4514)
12-26 14:36:18.547: W/System.err(9063):     at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:36:18.547: W/System.err(9063):     at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:36:18.547: W/System.err(9063):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-26 14:36:18.547: W/System.err(9063):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-26 14:36:18.555: W/System.err(9063):     at dalvik.system.NativeStart.main(Native Method)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T16:05:26+00:00Added an answer on June 16, 2026 at 4:05 pm

    After seeing you whole code and Log I had found few things and had one query.

    Query:

    1) Why are you using base64 for uploding images to server. There are many other way to upload images to server.

    Issue found:

    In second Code you had set socket connection Timeout and after seeing your log what I can see is the Connection to the server is taking time so your application is not able to upload anything to server and you are getting this Timeout Exception.

    Solution:

    1) Increase your Socket Connection Timeout time and then check once again.
    2) Use some different way to upload Images to server

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to send image and text data from Android phone to a Server.
I want to send more than one image file from client to server for
I want to send video/images from the android mobile to a server and recieve
I have some image data (jpeg) I want to send from my iPhone app
i want a two communication between server and Android. From Android want to send
Hello Sir i want send list of data to php server i use following
I would like to capture an image from the camera on Android, and send
I want to set the Image to be Selected from the Android Gallery. I
I want to pass image as well as some data from view to controller
I want to send an image to a web server running .Net which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.