android HttpURLConnection

本文介绍了如何使用Java中的HttpURLConnection对象实现基本的网络通信功能,包括获取网页数据、下载文件、发送请求参数及XML数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

转账自 http://blog.sina.com.cn/s/blog_5120ae140100mnnv.html

 

利用HttpURLConnection对象,我们可以从网络中获取网页数据.
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6* 1000);//设置连接超时
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
System.out.println(result);
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = -1;
    while( (len = inSream.read(buffer)) != -1 ){
        outStream.write(buffer, 0, len);
    }
    byte[] data = outStream.toByteArray();
    outStream.close();
    inSream.close();
    return new String(data, charsetName);
}
利用HttpURLConnection对象,我们可以从网络中获取文件数据.
URL url = new URL("http://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6* 1000);
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();
readAsFile(is, "Img269812337.jpg");

public static void readAsFile(InputStream inSream, File file) throws Exception{
    FileOutputStream outStream = new FileOutputStream(file);
    byte[] buffer = new byte[1024];
    int len = -1;
    while( (len = inSream.read(buffer)) != -1 ){
        outStream.write(buffer, 0, len);
    }
     outStream.close();
    inSream.close();
}

利用HttpURLConnection对象,我们可以向网络发送请求参数.
String requestUrl = "http://localhost:8080/itcast/contanctmanage.do";
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("age", "12");
requestParams.put("name", "中国");
 StringBuilder params = new StringBuilder();
for(Map.Entry<String, String> entry : requestParams.entrySet()){
    params.append(entry.getKey());
    params.append("=");
    params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    params.append("&");
}
if (params.length() > 0) params.deleteCharAt(params.length() - 1);
byte[] data = params.toString().getBytes();
URL realUrl = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);//发送POST请求必须设置允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");            
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data);
outStream.flush();
if( conn.getResponseCode() == 200 ){
        String result = readAsString(conn.getInputStream(), "UTF-8");
        outStream.close();
        System.out.println(result);
}
利用HttpURLConnection对象,我们可以向网络发送xml数据.
StringBuilder xml =  new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<M1 V=10000>");
xml.append("<U I=1 D=\"N73\">中国</U>");
xml.append("</M1>");
byte[] xmlbyte = xml.toString().getBytes("UTF-8");
URL url = new URL("http://localhost:8080/itcast/contanctmanage.do?method=readxml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6* 1000);
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");            
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(xmlbyte);//发送xml数据
outStream.flush();
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//获取返回数据
String result = readAsString(is, "UTF-8");
outStream.close(); 


Android中的HttpURLConnection是一个用于发送和接收HTTP请求的类。它是Java标准库中的一部分,并且在Android开发中被广泛使用。 使用HttpURLConnection可以执行以下操作: 1. 创建连接:使用URL对象创建HttpURLConnection对象,并设置连接的URL。 2. 设置请求方法:使用setRequestMethod()方法设置请求的方法,如GET、POST等。 3. 设置请求头:使用setRequestProperty()方法设置请求头信息,如Content-Type、User-Agent等。 4. 设置请求体:对于POST请求,可以使用OutputStream将数据写入请求体。 5. 发送请求:使用connect()方法建立与服务器的连接,并发送请求。 6. 获取响应码:使用getResponseCode()方法获取服务器的响应码。 7. 获取响应数据:根据响应码,可以使用getInputStream()或getErrorStream()方法获取服务器返回的数据流。 8. 解析响应数据:根据服务器返回的数据格式,可以使用相应的解析方式进行解析,如JSON解析、XML解析等。 以下是一个简单的示例代码,演示了如何使用HttpURLConnection发送GET请求并获取响应数据: ```java try { URL url = new URL("http://www.example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); // 处理响应数据 String responseData = response.toString(); // ... } else { // 处理错误情况 } } catch (IOException e) { e.printStackTrace(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值