HttpURLConnection方式
/**
* 采用HttpUrlConnection通信:请求方式为get
* 针对一般的文本数据传输,不包括图片等其他文件
* @return
*/
private String send2() {
// String validateURL = "http://zjx:8080/Test?name=yang";
String uri = "http://10.0.2.2:8080/HttpDemoServer/TestServlet?name=xingzjx&pwd=111";
// 1、创建一个HttpURLConnection连接
HttpURLConnection conn = null;
try {
// 2、创建一个URL对象,拿到uri地址
URL url = new URL(uri);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
// 3、建立到远程对象的实际连接
conn.connect();
// 4、成功后得到服务器返回的字符串
// DataInputStream dis = new DataInputStream(conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str = null;
StringBuffer sb = new StringBuffer();
while((str = br.readLine())!=null) {
sb.append(str);
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return sb.toString();
} else {
return "网络异常";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect(); // 中断连接
}
}
return "网络异常";
} |
|