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>
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>