HttpURLConnection请求网络数据的Post请求
Posted 巫山码农
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection请求网络数据的Post请求相关的知识,希望对你有一定的参考价值。
//--------全局变量-----------
//注册Url
private String urlPath="http://101.200.142.201:8080/VideoPlay/regist";
//----------------onCreate中---------------------------------
实现zhuce();方法
//--------注册方法--------------------
//注册方法
private void zhuce() {
new Thread(){
public void run() {
try {
//获得输入框输入的内容
String phonenum=et_phone_num.getText().toString().trim();
String password=et_password.getText().toString().trim();
String name=et_name.getText().toString().trim();
String queren_password=et_queren_password.getText().toString().trim();
//编码,将文字编码
String ss=URLEncoder.encode(name, "utf-8");
//使用HttpURLConnection获得网络数据
URL url=new URL(urlPath);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("POST");
urlConnection.connect();
String kk="userName="+ss+"&userPhone="+phonenum+"&userPassword="+password;
PrintWriter writer=new PrintWriter(urlConnection.getOutputStream());
writer.write(kk);
writer.flush();
writer.close();
int code=urlConnection.getResponseCode();
if (code==200) {
InputStream inputStream=urlConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String liner;
StringBuffer buffer=new StringBuffer();
while ((liner=reader.readLine())!=null) {
buffer.append(liner);
}
String str=buffer.toString();
//创建Message给handler发送消息
Message message=new Message();
message.what=1;
message.obj=str;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
//-------------使用Handler接受 消息并更新Ui-----------------
private Handler handler=new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
String text=(String) msg.obj;
tv_namess.setText(text);
break;
default:
break;
}
}
};
以上是关于HttpURLConnection请求网络数据的Post请求的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask异步加载和HttpURLConnection网络请求数据
AsyncTask异步加载和HttpURLConnection网络请求数据
安卓HttpURLConnection 进行http请求(传递数据 获取数据 主线程禁止网络请求)以get方式为例
httpURLConnection-网络请求的两种方式-get请求和post请求