Search code examples
androidhttppostdata

How do I Post Data in Android?


I've found this topic for PostData using http. but it doesn't work.

What's wrong?

I also requested Android.permission.INTERNET in the manifest.

    public void postData() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http:/mysite.com/postTest.php");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("pw", "12456"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        tv.setText(response.toString());
    } catch (ClientProtocolException e) {
        //
    } catch (IOException e) {
        //
    }
}

Edit

My application will be terminated with this message : Unfortunately PostDataProject has stopped.


Solution

  • try this:

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = responce.getEntity();
    // convert stream to String 
    BufferedReader buf = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder sb1 = new StringBuilder();
    String line = null;
    while ((line = buf.readLine()) != null) {
    sb1.append(line);
    }
    tv.setText(sb1.toString());
    

    and u can direclty set to textview if data is only for textvew or small:

    tv.setText(EntityUtils.toString(response.getEntity()));
    

    and use this:

    HttpPost httppost = new HttpPost("http://mysite.com/postTest.php");
    

    instead of

    HttpPost httppost = new HttpPost("http:/mysite.com/postTest.php");