注意:
1.安卓主线程禁止联网操作,如果在主线程中使用HttpURLConnection需通过new Thread()在新的线程中使用。
2.使用HttpURLConnection时必须设计异常处理。
3.get方式无法传递中文参数,如果需要传递中文参数则需要在前台和后台分别进行编解码 操作:get 方式传递中文_fade-CSDN博客
1.创建URL对象,并传递参数
String path="http://xxx.xx.xxx.xx/xxxxx?x=52&y=4554"
URL url = new URL(path);
在get方式中,如果需要传递参数,格式如上所示。每个参数之间用&分割。问号后表示向服务器传递两个参数x和y,x=52,y=4554。如果参数的数据不是固定的,可以用“xxxx=”+变量名的方式设置path字符串。如
String path="http://xxx.xx.xxx.xx/xxxxx?"+"x="+x+"&"+"y="+y;
2.获取HttpURLConnection的对象实例
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
3.设置请求方式与其他参数
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);//超时时间
conn.setReadTimeout(6000);//响应时间
4.获取输入流,并进行格式转换
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}//输入流转字符流
reader.close();//关闭输入流
Log.i("x",buffer.toString());//输出测试
5.关闭http连接
conn.disconnect();
完整代码如下
public void onClick(View view) {
new Thread(){
@Override
public void run() {
try {
int x=800;
int y=2500;
String path="http://xxx.xx.xxx.xx/xxxxx?"+"x="+x+"&"+"y="+y;
URL url = new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);//超时时间
conn.setReadTimeout(6000);//响应时间
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
Log.i("x",buffer.toString());
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}