加入网络权限 AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
public boolean dealLogin() {
boolean bLogin = false;//
String StrResponseBody = null;
String strUrl = "http://www.appio.cn/WebTest/LoginCheck";
String username = "admin";
String password = "1234";
String strData = "username=" + username + "&password=" + password;
try{
byte[] requestBody = strData.getBytes( "UTF-8" );
URL url = new URL( strUrl );
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Length", String.valueOf( requestBody.length));//设置请求体的长度
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write( requestBody );
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
//获得响应体的字节数组
StrResponseBody = dealResponseResult( inptStream );
if ( StrResponseBody == "OK" )
{
bLogin = true;
}
//获得响应头
//responseHeader = getResponseHeader(conn);
}//if
}catch (IOException e) {
e.printStackTrace();
//return "err: " + e.getMessage().toString();
}
//
return bLogin;
}
public String dealResponseResult(InputStream inputStream) { String resultData = null; //存储处理结果 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; try { while((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } } catch (IOException e) { e.printStackTrace(); } resultData = new String(byteArrayOutputStream.toByteArray()); return resultData; }