您的位置:首页 > 理论基础 > 计算机网络

Android中利用HttpURLConnection发送Post请求并添加参数的写法

2016-05-15 23:54 1316 查看
利用HttpURLConnection提交参数的时候,只能使用IO流的方式来进行提交。

URL url = new URL(“http://172.60.50.141:8080/ems/regist.do“);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

//设定网络访问的方式,注意POST必须大写

connection.setRequestMethod(“POST”);

//要获得服务器的内容,需要设置setDoInput(true)

connection.setDoInput(true);

//要向服务器提交参数,需要设置setDoOutput(true)

connection.setDoOutput(true);

//设置请求头中的内容,对请求实体中的参数内容进行说明

connection.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);

//设定参数

connection.connect();

//HttpURLConnection提交参数的时候需要通过IO流的方式来进行

//而且一定要先利用输出流提交参数后才能取通过获得输入流拿到正确的服务器响应

OutputStream out = connection.getOutputStream();

PrintWriter pw = new PrintWriter(out);

String params=”“;

//因为HttpURLConnection没有HttpClient那样BasicNameValuePair的辅助类

//因此使用HashMap来进行手动构造键值对的存储形式

HashMap
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: