android网络编程——http post

        前一篇给出了HttpGet的实例,这一篇给出HttpPost的实例。

public class HttpPostDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        BufferedReader in = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost("http://mysomewebsite.com/services/doSomething.do");
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("username", "test"));
            postParameters.add(new BasicNameValuePair("password", "test1234"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);

            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(
            		new InputStreamReader(
            				response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            System.out.println(result);
        } catch(Exception e) {
        	// Do something about exceptions
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
* @author 张兴业
* 邮箱: xy-zhang#163.com
* android开发进阶群: 278401545
*
*/

你可能感兴趣的:(android,http,android,http,http,网络,post,post)