android中简单的HTTP通信

来源:互联网 发布:java分布式开发应用pdf 编辑:程序博客网 时间:2024/04/29 04:53
anddroid中简单的HTTP通信
 private String getHttpResponse(String location) {
  String result = null;
  URL url = null;
  
try {
  
 url = new URL(location);
  } catch (MalformedURLException e) {
   Log.e(tag, location + "is not a rihgt url", e);
  }
  if (url != null) {
   HttpURLConnection urlConn = null;
   InputStream is = null;
   OutputStream os=null;
   try {
    urlConn = (HttpURLConnection) url.openConnection();
    os=urlConn.getOutputStream();
    os.write("Hello".getBytes());
    is = urlConn.getInputStream();
    byte buffer[] = new byte[is.available()];
    is.read(buffer);
    result=new String(buffer);
   } catch (IOException e) {
   } finally {
    try {
     if (is != null)
      is.close();
    } catch (IOException e) {
    }
    urlConn.disconnect();
   }
  }
  return result;
 }
注意:需要加入以下权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
原创粉丝点击