¿Cómo pasar un valor usando HTTPPost?

I am working on this code to post a value say name of a person into a web page but due to some reason it not working... to some extend it is working. i have given some print sequence in code which gets displayed in logcat....

este es mi MainActivity

public class MainActivity extends Activity {
String link="http://myweb.com/index.php";
String name1 = "akhil";
String value="name"+name1;
Button bttn1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            try{
            post_connection obj = new post_connection();
            obj.connect(link,value);                
            }
            catch (Exception e) {
                // TODO: handle exception
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });        

}   

}

My post_connection class is given below

public class post_connection {

public void connect(String link , String value)
{

    try
    {
        URLConnection url = new URL(link).openConnection();
        if(url instanceof HttpURLConnection) {


              // do stuff

            System.out.println("@@@3");
            System.out.println("@@@3");

            System.out.println("@@@32");
            ((HttpURLConnection) url).setRequestMethod("POST");
            ((HttpURLConnection) url).setAllowUserInteraction(true);
            ((HttpURLConnection) url).setDoInput(true);
            ((HttpURLConnection) url).setDoOutput(true);
            ((HttpURLConnection) url).setUseCaches(true);
            System.out.println("@@@4");
            System.out.println("Making the request");
            ((HttpURLConnection)url).connect();
            System.out.println("connecting.....");

            DataOutputStream data = new DataOutputStream(((HttpURLConnection) url).getOutputStream());
            data.writeBytes(value);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(((HttpURLConnection) url).getInputStream()));
            System.out.println("@@@5");
            String decodedString;
            while((decodedString=bufferedReader.readLine())!=null)
            {
                System.out.println("decoded::"+decodedString);
            }
            bufferedReader.close();
            }
            else {
              // error?
                System.out.println("@@@23");
            }

    }
    catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }


}

}

this shows a logcat output like this

preguntado el 31 de julio de 12 a las 12:07

3 Respuestas

Try URL Re-Writting as following:

url = url+"?Param1=Value1&Param2=value2";
           ^ Rewriter    ^ Parameter Delimeter

and then post above edited url.

Respondido 31 Jul 12, 12:07

Puede probar:

    public static String makePostRequest(String url, Bundle params) throws IOException {
         HttpClient httpclient = new DefaultHttpClient();      
         HttpPost httppost = new HttpPost(url);
         List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
         for (String key : params.keySet()) {
             postParameters.add(new BasicNameValuePair(URLEncoder.encode(key), URLEncoder.encode(params.getString(key))));
         }
         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
         httppost.setEntity(formEntity);
         ResponseHandler<String> responseHandler = new BasicResponseHandler();
         return httpclient.execute(httppost, responseHandler);
    }

Respondido 31 Jul 12, 12:07

You can rewrite the post_connection class as follow:

public class post_connection {

public void connect(String link , String value){


try
{
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    HttpPost httpost;
    String responseString = null;

        // do stuff


        httpost = new HttpPost(link);

    /*StringEntity se = new StringEntity(value);

        httpost.setEntity(se);*/


       List<NameValuePair> params = new ArrayList<NameValuePair>();

       params.add(new BasicNameValuePair("name", value));

       UrlEncodedFormEntity formEntity = null;
       try {
            formEntity = new UrlEncodedFormEntity(params);

        } catch (UnsupportedEncodingException e1) {


        }

         httppost.setEntity(formEntity);

        System.out.println("Making the request");

        response = httpclient.execute(httpost);

        //getting the response

        StatusLine statusLine = response.getStatusLine();

        if(statusLine.getStatusCode() == HttpStatus.SC_OK){

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();


        } else{

            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }

} 
catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
}

}

Respondido 02 ago 12, 23:08

<?php mysql_connect("mysql4.000webhost.com","a2271273_test","test123"); mysql_select_db("a2271273_test"); echo $_POST['name']; if(isset($_POST['name'])){ $name=$_POST['name']; $result=mysql_query("INSERT INTO test (name) VALUES ('$name')"); if($result>0){ echo "sucess"; } else{ echo "failed"; } } ?> - Akhil

i am using php page to receive the data by $_POST method.But i cant receive the string "value" in that page..can u please help me?? - Akhil

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.