2013-05-07 102 views
0

情況:Android - 客戶端服務器,發佈請求

我正在使用客戶端 - 服務器通信。

當用戶保存數據(產品名稱,圖片,註釋)時,應將其傳送到數據庫的服務器端。

但是,我不知道如何在客戶端(Android)上編碼http Post請求。

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

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

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

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); 
     } 
    }); 

} 

} 

這是我的代碼。 請幫助我如何在此代碼中添加http post請求.. 而且還在服務器端的php。

回答

0

爲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(); 

欲瞭解更多有關如何調用PHP Web服務有一個相當不錯的教程,可以發現here

相關問題