首页 > 代码库 > HttpURLConnection请求网络数据的Post请求
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请求