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

Android使用HttpURLConnection发送Get请求

2015-03-10 18:00 323 查看
private void getDataByHttp()
{
String strUrl = "http://192.168.1.113:8080/TestHttp/MyJsp.jsp";
strUrl += "?";
try
{
strUrl += "userName=" + URLEncoder.encode("测试", "UTF-8");
strUrl += "&userPassword=" + "123456";

System.out.println(strUrl);
} catch (UnsupportedEncodingException e1)
{
e1.printStackTrace();
}

String resultData= "";
URL url = null;
try
{
url = new URL(strUrl);
} catch (MalformedURLException e)
{
e.printStackTrace();
}

if(url != null)
{
HttpURLConnection httpURLConnection = null;
try
{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
if(httpURLConnection.getResponseCode() != 200)
{
Log.e("链接失败","返回不是200--" + httpURLConnection.getResponseCode());
Message msg = new Message();
msg.what = 2;
handler.sendMessage(msg);
return;
}
InputStream input = httpURLConnection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(streamReader);

String inputLine = null;

while((inputLine = bufferedReader.readLine()) != null)
{
resultData  += inputLine + "\r\n";
}

bufferedReader.close();
streamReader.close();
input.close();
httpURLConnection.disconnect();
<span style="white-space:pre">				</span>System.out.println(resultData);
} catch (IOException e)
{
e.printStackTrace();

}

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