作者:书友47721235_104 | 来源:互联网 | 2023-01-29 17:09
使用HC(HttpClient)UC(HttpURLConnection)进行网络访问的基本步骤:1.申请权限INTERNET访问权限2.任何网络访问的相关代码,必须在工
使用HC(HttpClient)/UC(HttpURLConnection)进行网络访问的基本步骤:
1.申请权限 INTERNET访问权限
2. 任何网络访问的相关代码,必须在工 作线程中执行!
3. 创建HC/UC对象
4. 声明发起网络访问的方式(GET/POST)
5. 进行网络连接
6. 获得服务器响应的结果
7. 解析结果,提取需要的内容
8. 解析结果要提交到UI线程进行呈现
- HttpUrlConnection的POST请求的Demo:
URL url = new URL("http://172.60.10.117:8080/ems/regist.do")
HttpURLConnection cOnnection= (HttpURLConnection) url.openConnection()
connection.setRequestMethod("POST")
connection.setDoInput(true)
connection.setDoOutput(true)
// 在请求头中。为请求实体中的内容作说明
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded")
connection.connect()
//客户端向服务器提交参数
OutputStream outputStream = connection.getOutputStream()
PrintWriter printWriter = new
String params =
"loginname ="+user.getName()+"password="+user.getPassWord()
+"realname="+user.getRealname()+"email="+user.getEmail()
printWriter.print(params)
printWriter.close()
InputStream inputStream = connection.getInputStream()
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream))
final String result = bufferedReader.readLine()
bufferedReader.close()
inputStream.close()
总结:这里面需要注意的是请求的头部文件:
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded")
注意设置请求方式的时候:
connection.setRequestMethod("POST");
2.、HttpClient的Post请求数据的Demo:
利用HttpClient的POST方式发起带参数的请求
利用POST方式发起请求,参数要放到请求实体中,并且在请求头中添加对实体中参数的说明。
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://172.60.10.117:8080/ems/login.do");
request.setHeader("Content-Type","application/x-www-form-urlencoded");
List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("loginname",loginUser.getName()));
parameters.add(new BasicNameValuePair("password",
loginUser .getPasswrod()));
parameters.add(new BasicNameValuePair("code",
loginUser .getCode()));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
request.setEntity(entity);
HttpResponse httpRespOnse= client.execute(request);
EntityUtils.toString(httpResponse.getEntity());
后面返回的数据是JSON数据,希望大家能够看过这篇博客后,能够有所收获!