通过Web服务将图像从Android发送到数据库

时间:2015-07-04 09:25:54

标签: java c# android web-services wcf

我写了这样的Android客户端:

清单文件

<?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代码,我从EditText s,TextView等获取值。我正在使用{{1}调用web service method下面。然后Web服务方法(应该)将传入的数据插入数据库。 我在将图像发送到网络服务方面遇到了麻烦。因为,URL的长度超过100.000个字符......

我认为这种方法(在Android应用中调用URL)没用。

网络服务代码:

IService.cs

URL

Service.svc.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);     
    }
}

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

感谢。 :)

1 个答案:

答案 0 :(得分:0)

要将图像从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();
    }

导入 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