【问题标题】:send image from Android through Web Service to database通过 Web 服务将图像从 Android 发送到数据库
【发布时间】:2015-07-04 09:25:54
【问题描述】:

我是这样写安卓客户端的:

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tests.com.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- other codes.... -->

活动类

public class Registration extends ActionBarActivity {
    /***************** local variables ******************/
    int gun, ay, il;
    Button submit, clear;
    TextView profile_pic, birthday;
    EditText username, password, name, surname, graduated_from, graduated_in, born_place;
    ImageView imageview;
    private String convertedImage = null;
    private byte[] inputData = null;
    /***************** local variables ******************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);


    /***************** get values from view elements ******************/
    submit = (Button) findViewById(R.id.submit);
    clear = (Button) findViewById(R.id.clear);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    name = (EditText) findViewById(R.id.name);
    surname = (EditText) findViewById(R.id.surname);
    graduated_from = (EditText) findViewById(R.id.graduated_from);
    graduated_in = (EditText) findViewById(R.id.graduated_in);
    born_place = (EditText) findViewById(R.id.born_place);
    birthday = (TextView) findViewById(R.id.birthday);
    profile_pic = (TextView) findViewById(R.id.profile_pic);
    imageview = (ImageView) findViewById(R.id.imageView);
    /***************** get values from view elements ******************/


    /***************** set calendar to current date ******************/
    final Calendar calendar = Calendar.getInstance();
    gun = calendar.get(Calendar.DATE);
    ay = calendar.get(Calendar.MONTH);
    il = calendar.get(Calendar.YEAR);
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    /***************** set calendar to current date ******************/


    View.OnClickListener button_click = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.submit: // "Submit" button
                    String istiad = username.getText().toString();
                    String sifre = password.getText().toString();
                    String ad = name.getText().toString();
                    String soyad = surname.getText().toString();
                    String bitirdiyi_mekteb = graduated_from.getText().toString();
                    String bitirdiyi_il = graduated_in.getText().toString();
                    String dogum_yeri = born_place.getText().toString();
                    String dogum_ili = birthday.getText().toString();
                    String profile_pic = convertedImage;

    // construct URL for async task
                    String URL = "http://localhost/wcf/Service.svc/register/" + istiad + "/" + sifre + "/" + ad + "/" + soyad + "/" + bitirdiyi_mekteb + "/" + bitirdiyi_il + "/" + dogum_yeri + "/" + dogum_ili; //+ "/" + profile_pic;
                    // call WebService
                    new HttpAsyncTask().execute(URL);
                    break;
                case R.id.clear:  // "Clear" button
                    ViewGroup group = (ViewGroup) findViewById(R.id.form);
                    clearForm(group);
                    break;
                case R.id.birthday: // "birthday" TextView
                    showDialog(0);
                    break;
                case R.id.profile_pic: // "profile_pic" TextView
                    getImage();
                    break;
            }
        }

    };

    submit.setOnClickListener(button_click);
    clear.setOnClickListener(button_click);
    birthday.setOnClickListener(button_click);
    profile_pic.setOnClickListener(button_click);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();

    imageview.setImageURI(selectedImage);

    Bitmap bitmap = ((BitmapDrawable) imageview.getDrawable()).getBitmap();
                    convertedImage = Base64.encodeToString(getBytesFromBitmap(bitmap), Base64.URL_SAFE);
                    name.setText(convertedImage);
                }
                break;
        }
    }

    public byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }

    public static String GET(String URL) {
        String result = "";

    try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(URL);
            HttpResponse response;
            try {
                response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            result = e.getLocalizedMessage();
        }
        return result;
    }


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return GET(urls[0]);
        }

    @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Done!", LENGTH_LONG).show();
        }
    }
}

如您所见,通过这些 Java 代码,我从 EditTexts、TextView 等处获取值。我正在使用下面的 URL 调用 web service method。然后 Web 服务方法(应该)将传入的数据插入数据库。 我在将图像发送到网络服务时遇到问题。因为,URL 的长度超过了 100.000 个字符...

我认为这种方法(在 android 应用程序中调用 URL)没有用。

网络服务代码:

IService.cs

namespace WebService
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/register/{username}/{password}/{name}/{surname}/{graduated_from}/{graduated_in}/{born_place}/{birthday}/{profile_pic}")]
        string register(string username, string password, string name, string surname, string graduated_from, string graduated_in, string born_place, string birthday, string profile_pic);     
    }
}

Service.svc.cs

namespace WebService
{
    public class Service : IService
    {
        private static MySqlConnection connection = new MySqlConnection("server=45.35.4.29;uid=root;password=connection;database=db_webservice");

        // http://stackoverflow.com/q/472906
        // http://stackoverflow.com/q/1003275
        // http://stackoverflow.com/q/10513976
        public class Convert
        {
            public static byte[] ConvertToBytes (string str)
            {
                byte[] bytes = new byte[str.Length * sizeof(char)];
                Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);

                return bytes;
            }

            public static string ConvertToString (byte[] bytes)
            {
                char[] chars = new char[bytes.Length / sizeof(char)];
                Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);

                return new string(chars);
            }
        }


        // https://youtu.be/iqrY9IaUY24
        // https://youtu.be/AMH4plUP0uo
        public string register (string username, string password, string name, string surname, string graduated_from, string graduated_in, string born_place, string birthday) //, string profile_pic)
        {
            bool result = false;

            string query_insert = @"INSERT INTO users(username, password, name, surname, graduated_from, graduated_in, born_place, birthday) VALUES( ' " + username + " ', ' " + password + " ', ' " + name + " ', ' " + surname + " ', ' " + graduated_from + " ', ' " + graduated_in + " ', ' " + born_place + " ', ' " + birthday + " ' );";

            if (connection.State == ConnectionState.Closed)
                connection.Open();

            using (MySqlCommand insert = new MySqlCommand(query_insert, connection))
            {
                insert.ExecuteNonQuery();
                result = true;
            }

            if (result)
                return "success";
            else
                return "fail";
        }
    }
}

任何评论和/或答案将不胜感激!

谢谢。 :)

【问题讨论】:

    标签: java c# android web-services wcf


    【解决方案1】:

    要将图像从 android 设备上传到远程服务器,您可以使用以下代码。

    HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 200000);
        String resFromServer = "";
        HttpResponse response;
    
        HttpPost httppost = new HttpPost(api_url);
        File file = new File(imagePath);
        ContentBody cbFile = new FileBody(file, "image/jpeg");
        try {
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("user_profile_image", cbFile);
            httppost.setEntity(reqEntity);
            httppost.addHeader("enctype", "multipart/form-data");
            String base64EncodedCredentials = Base64.encodeToString(
                    credentials.getBytes(), Base64.NO_WRAP);
            httppost.addHeader("Authorization", "Basic "
                    + base64EncodedCredentials);
    
            response = client.execute(httppost);
            resFromServer = org.apache.http.util.EntityUtils.toString(response
                    .getEntity());
        }catch(Exception exp){
         exp.printStack();
        }
    

    import org.apache.http.entity.mime.content.ContentBody ,org.apache.http.entity.mime.content.FileBody 包来实现它。为此,您必须包含以下内容jar 文件到您的项目中

    apache-mime4j-0.6.jar httpmime-4.1-beta1.jar

    【讨论】:

    • 谢谢! ContentBodyFileBody 类是什么?
    • import org.apache.http.entity.mime.content.ContentBody ,org.apache.http.entity.mime.content.FileBody 包来实现它。为此,您必须包含以下 jar 文件到你的项目。我更新了答案
    • 你能解释一下我的安卓应用程序出了什么问题吗?为什么?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多