简体   繁体   English

Android-客户端服务器,发布请求

[英]Android - Client Server, Post Request

Situation : 情况:

I am working on Client-Server Communication. 我正在进行客户端-服务器通信。

When the users save the data (name of product, image, note), it should be transferred to the server side of the database. 当用户保存数据(产品名称,图像,注释)时,应将其传输到数据库的服务器端。

But, I don't know how to code http Post request on the client side(Android). 但是,我不知道如何在客户端(Android)上编码http Post请求。

MyWishlistsActivity.java MyWishlistsActivity.java

public class MyWishlistsActivity extends ListActivity {


SQLiteConnector sqlCon;
private CustomWishlistsAdapter custAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    String[] from = new String[] { Wishlists.NAME, Wishlists.NOTE };
    int[] to = new int[] { R.id.name };
    custAdapter = new CustomWishlistsAdapter(this,R.layout.wishlist_list_item, null, from, to);
    this.setListAdapter(custAdapter);   

}

@Override
protected void onResume() {
    super.onResume();
    new GetContacts().execute((Object[]) null);
}

@SuppressWarnings("deprecation")
@Override
protected void onStop() {
    Cursor cursor = custAdapter.getCursor();

    if (cursor != null)
        cursor.deactivate();

    custAdapter.changeCursor(null);
    super.onStop();

}

private class GetContacts extends AsyncTask<Object, Object, Cursor> {
    SQLiteConnector dbConnector = new SQLiteConnector(MyWishlistsActivity.this);

    @Override
    protected Cursor doInBackground(Object... params) {
        return dbConnector.getAllWishlists();  
    }

    @Override
    protected void onPostExecute(Cursor result) {
        custAdapter.changeCursor(result);
        }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent addWishlists = new Intent(MyWishlistsActivity.this,AddEditWishlists.class);
    startActivity(addWishlists);
    //Client-Server
    Intent addWishlists2 = new Intent(MyWishlistsActivity.this,Server_AddWishlists.class);
    startActivity(addWishlists2);
    //Client-Server End
    return super.onOptionsItemSelected(item);
 }  
}

AddWishlists.java AddWishlists.java

public class AddEditWishlists extends Activity {


private EditText inputname;
private EditText inputnote;
private Button upload;
private Bitmap yourSelectedImage;
private ImageView inputphoto;
private Button save;
private int id;
private byte[] blob=null;
byte[] image=null;

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

private void setUpViews() {

    inputname = (EditText) findViewById(R.id.inputname);
    inputnote = (EditText) findViewById(R.id.inputnote);
    inputphoto = (ImageView) findViewById(R.id.inputphoto); 

    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        id=extras.getInt("id");
        inputname.setText(extras.getString("name"));
        inputnote.setText(extras.getString("note"));
        image = extras.getByteArray("blob");

        if (image != null) {
            if (image.length > 3) {
                inputphoto.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }

    }




    upload = (Button) findViewById(R.id.upload);
    upload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, 0);
        }
    });

    save = (Button) findViewById(R.id.save);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (inputname.getText().length() != 0) {
                AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                        saveContact();
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Object result) {
                        finish();
                    }
                };

                saveContactTask.execute((Object[]) null);
            } else {
                AlertDialog.Builder alert = new AlertDialog.Builder(
                        AddEditWishlists.this);
                alert.setTitle("Error In Save Wish List");
                alert.setMessage("You need to Enter Name of the Product");
                alert.setPositiveButton("OK", null);
                alert.show();
            }
        }
    });
}

private void saveContact() {

    if(yourSelectedImage!=null){
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        yourSelectedImage.compress(CompressFormat.JPEG, 100, outStr);
        blob = outStr.toByteArray();
    }

    else{blob=image;}

    SQLiteConnector sqlCon = new SQLiteConnector(this);

    if (getIntent().getExtras() == null) {
        sqlCon.insertWishlist(inputname.getText().toString(), inputnote.getText().toString(), blob);
    }

    else {
        sqlCon.updateWishlist(id, inputname.getText().toString(), inputnote.getText().toString(),blob);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode,Intent resultdata) {
    super.onActivityResult(requestCode, resultCode, resultdata);
    switch (requestCode) {
    case 0:
        if (resultCode == RESULT_OK) {
            Uri selectedImage = resultdata.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);

            cursor.close();
            // Convert file path into bitmap image using below line.
            yourSelectedImage = BitmapFactory.decodeFile(filePath);
            inputphoto.setImageBitmap(yourSelectedImage);
        }

    }
}

}

ViewWishlist.java ViewWishlist.java

public class ViewWishlist extends Activity {

private TextView name;
private TextView note;
private ImageView photo;
private Button backBtn;
private byte[] image;

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

private void setUpViews() {
    name = (TextView) findViewById(R.id.inputname);
    note = (TextView) findViewById(R.id.inputnote);
    photo = (ImageView) findViewById(R.id.inputphoto);


    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        name.setText(extras.getString("name"));
        note.setText(extras.getString("note"));
        image = extras.getByteArray("blob");

        if (image != null) {
            if (image.length > 3) {
                photo.setImageBitmap(BitmapFactory.decodeByteArray(image,0,image.length));
            }
        }

    }

    backBtn=(Button)findViewById(R.id.back);
    backBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    });

}

}

CustomWishlistsAdapter.java CustomWishlistsAdapter.java

public class CustomWishlistsAdapter extends SimpleCursorAdapter {

private int layout;
private ImageButton editBtn;
private ImageButton delBtn;
LayoutInflater inflator;

public CustomWishlistsAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
    super(context, layout, c, from, to,0);
    this.layout = layout;
    inflator= LayoutInflater.from(context);
}

public View newView(Context context, Cursor cursor, ViewGroup parent) {     
    View v = inflator.inflate(layout, parent, false);
    return v;
}

@Override
public void bindView(View v, final Context context, Cursor c) {
    final int id = c.getInt(c.getColumnIndex(Wishlists.ID));
    final String name = c.getString(c.getColumnIndex(Wishlists.NAME));
    final String note = c.getString(c.getColumnIndex(Wishlists.NOTE));
    final byte[] image = c.getBlob(c.getColumnIndex(Wishlists.IMAGE));
    ImageView iv = (ImageView) v.findViewById(R.id.inputphoto);

    if (image != null) {
        if (image.length > 3) {
            iv.setImageBitmap(BitmapFactory.decodeByteArray(image, 0,image.length));
        }
    }

    TextView tname = (TextView) v.findViewById(R.id.name);
    tname.setText(name);

    final SQLiteConnector sqlCon = new SQLiteConnector(context);

    editBtn=(ImageButton) v.findViewById(R.id.edit_btn);    
    editBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,AddEditWishlists.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            intent.putExtra("note", note);
            intent.putExtra("blob", image);
            context.startActivity(intent);
        }

    });

    delBtn=(ImageButton) v.findViewById(R.id.del_btn);  
    delBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            sqlCon.deleteWishlist(id);  
            Intent intent=new Intent(context,MyWishlistsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }

    });     

    v.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,ViewWishlist.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            intent.putExtra("note", note);
            intent.putExtra("blob", image);
            context.startActivity(intent);
        }
    });

}

}

This is my code. 这是我的代码。 Please help me how to add http post request on this code.. And also the php on the Server side . 请帮助我如何在此代码上添加http post请求。以及服务器端的php。

For the Android HttpPost (to send JSON serialized data to a server) 对于Android HttpPost(用于将JSON序列化的数据发送到服务器)

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("url_of_the_server");
JSONObject json = new JSONObject();
json.put("name", name);
json.put("note", note);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
//With response you can check the server return status code(to check if the request has been made correctly like so
StatusLine sLine = response.getStatusLine();
int statusCode = sLine.getStatusCode();

For more information on how to call a php web service there is a pretty nice tutorial that can be found here 有关如何调用php Web服务的更多信息,有一个很好的教程,可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android向SQL Server发布日期时间请求 - Android post request for datetime to SQL Server Android HTTP POST请求到服务器(需要说明) - Android HTTP POST request to server (need explanation) 从android的模拟器到服务器的POST请求 - POST request from emulator of android to a server Android - 向服务器发送发布请求时出现异常 - Android - Exceptions while sending post request to the server Android Post请求未在服务器上发布任何数据 - Android Post request not posting any data on server 具有标题和正文的Android异步Http客户端(Loopj)POST请求 - Android Asynchronous Http Client (Loopj) POST request with headers and body 如何使用 okhttp 客户端在 Android 中重定向发布请求 - How to redirect a post request in Android using okhttp client 无法处理对服务器的android post请求并将结果返回给android - Cannot process android post request to server and receive result back to android 在Android Java中使用GET \\ POST从客户端调用服务器方法 - calling server methods with GET\POST from client in android Java MJSIP:向服务器注册android客户端:onUaRegistrationFailure; Wireshark 400 /错误请求 - MJSIP: Register android client with server: onUaRegistrationFailure; Wireshark 400/Bad Request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM