URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL(“http://10.0.2.2:8888/data/get/?token=alexzhou”);
connection = (HttpURLConnection) url.openConnection();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
注意:因为是通过android模拟器访问本地pc服务端,所以不能使用localhost和127.0.0.1,使用127.0.0.1会访问模拟器自身。Android系统为实现通信将PC的IP设置为10.0.2.2
(2)post请求
public String executeHttpPost() {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL(“http://10.0.2.2:8888/data/post/”);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod(“POST”);
connection.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
connection.setRequestProperty(“Charset”, “utf-8”);
DataOutputStream dop = new DataOutputStream(
c