0

Please look into this my previous question on Stackoverflow


Since i could not figure solve my problem, i had come up with a different approach

now i have used two post functions

  • one for multipart image posting ------------ >postImageData()
  • another for string data posting ------------ > postData()

I am trying to post a single image as a multipart and a string data without multipart

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;
    InputStream is;

    EditText name;
    ImageView imageView;

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

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        name = (EditText) findViewById(R.id.editText1);
        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }

    public void postData() {

        String newurl = "?" + "key1=" + name.getText().toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2:7002/Details/"+newurl);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("key1", name.getText()
                    .toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.v("Response", response.toString());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }


    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException 
     */
    public void postImageData() {


        try
        {

            Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image); 

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            try{
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
                reqEntity.addPart("key", bab);
                //reqEntity.addPart("key1", new StringBody(name.getText().toString()));
            }
            catch(Exception e){
                //Log.v("Exception in Image", ""+e);
                reqEntity.addPart("picture", new StringBody(""));
            }
            postRequest.setEntity(reqEntity);       
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
        }catch(Exception e){
            e.getStackTrace();
        }


    }
    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            postImageData();
            postData();

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

Problem i am facing::

  • Currently all the operations of postImageData() are working fine
  • but postData() objective is not solved
  • Server side i am getting error Cannot read property 'key' of undefined

Note :: i checked that server is correctly working when data is sent with POSTMAN


[Edit]

test i found successful with postman

enter image description here

Community
  • 1
  • 1
smriti3
  • 871
  • 2
  • 15
  • 35

4 Answers4

0

For that you have to pass the key which is on server side:

Like: if your server side you have defined your key as a "picture" then on client side when you have to post that data to server you have to pass that key name as a parameter.

Like:

  reqEntity.addPart("picture", bab);
Piyush
  • 18,895
  • 5
  • 32
  • 63
  • @ Piyush Gupta ........ Have a look at my edit ....... if my test with postman as i posted values is working ......... then why not my android code ? ..... POST-MAN is similar to android client for making requests – smriti3 Dec 13 '13 at 12:13
  • @ Raghunandan .... Reaason i used POSTMAN is to confirm when i simulate a request ... server accepts it or not .... then i can pinpoint the problem !(Its just a experience from noob like me) ... any suggestions on my try at solving the problem ...with the code i posted – smriti3 Dec 13 '13 at 12:18
  • @smriti3 no i am not talking about POSTMAN. i am talking about your .... in almost all your comments which is unnecessary. Avoid it pls. – Raghunandan Dec 13 '13 at 12:29
0
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(jsonObjSend.length());
            nameValuePairs.add(new BasicNameValuePair("data", jsonObjSend.toString()));
           // Log.i("jsonObjSend.toString()","jsonObjSend.toString()"+jsonObjSend.toString());

            Log.i("HTTPPOST","URL: "+URL);
            Log.i("HTTPPOST","Request: "+jsonObjSend.toString());
            UrlEncodedFormEntity en=new UrlEncodedFormEntity(nameValuePairs);
            en.getContent();
            httpPostRequest.getParams().setParameter("http.socket.timeout", new Integer(600000));
            httpPostRequest.setEntity(en);
            long t = System.currentTimeMillis();
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
            Log.i(TAG, httpPostRequest.getRequestLine().getProtocolVersion().toString());
            responses = convertEntityToString(response.getEntity(), "UTF-8");
            Log.i("HTTPPOST","Responce: "+responses);
            Log.i("HTTPPOST","******************");

please check this code

dipali
  • 10,966
  • 5
  • 25
  • 51
0

Try to send the image as base64 string . Like the one given below

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap     object   
    byte[] byteArrayImage = baos.toByteArray(); 
    String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
Pramod J George
  • 1,723
  • 12
  • 24
0

use that android code for save to database

nameValuePairs2 = new  ArrayList<NameValuePair>();
     nameValuePairs2.add(new BasicNameValuePair("username",username));
    nameValuePairs2.add(new BasicNameValuePair("password",password));
 try{
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost(mainurl+"registration.php");
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 HttpResponse response = httpclient.execute(httppost);
                 String the_string_response = convertResponseToString(response);
             //    Toast.makeText(getApplicationContext(), "Response " + the_string_response, Toast.LENGTH_LONG).show();
             }catch(Exception e){
                 //  Toast.makeText(getApplicationContext(), "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
                //   System.out.println("Error in http connection "+e.toString());
             } 

create registration.php file save on server...for insert data to local database

The Ray of Hope
  • 738
  • 1
  • 6
  • 16