anddroid中简单的HTTP通信
privateStringgetHttpResponse(Stringlocation){
Stringresult=null;
URLurl=null;
try{
url=newURL(location);
}catch(MalformedURLExceptione){
Log.e(tag,location+"isnotarihgturl",e);
}
if(url!=null){
HttpURLConnectionurlConn=null;
InputStreamis=null;
OutputStreamos=null;
try{
urlConn=(HttpURLConnection)url.openConnection();
os=urlConn.getOutputStream();
os.write("Hello".getBytes());
is=urlConn.getInputStream();
bytebuffer[]=newbyte[is.available()];
is.read(buffer);
result=newString(buffer);
}catch(IOExceptione){
}finally{
try{
if(is!=null)
is.close();
}catch(IOExceptione){
}
urlConn.disconnect();
}
}
returnresult;
}
注意:需要加入以下权限
<uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>
privateStringgetHttpResponse(Stringlocation){
Stringresult=null;
URLurl=null;
try{
url=newURL(location);
}catch(MalformedURLExceptione){
Log.e(tag,location+"isnotarihgturl",e);
}
if(url!=null){
HttpURLConnectionurlConn=null;
InputStreamis=null;
OutputStreamos=null;
try{
urlConn=(HttpURLConnection)url.openConnection();
os=urlConn.getOutputStream();
os.write("Hello".getBytes());
is=urlConn.getInputStream();
bytebuffer[]=newbyte[is.available()];
is.read(buffer);
result=newString(buffer);
}catch(IOExceptione){
}finally{
try{
if(is!=null)
is.close();
}catch(IOExceptione){
}
urlConn.disconnect();
}
}
returnresult;
}
注意:需要加入以下权限
<uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>
本文介绍了在Android应用中如何使用简单的HTTP通信方法发送请求并获取响应,包括创建URL、打开连接、写入数据、读取输入流以及处理响应字符串等步骤,并强调了需要加入Internet权限。
641

被折叠的 条评论
为什么被折叠?



