Ikuta Erika

导航

HttpURLConnection类的使用

此类以获取天气的一个api地址为例:

package javaexcjs;

import java.io.BufferedReader;
import java.io.OutputStreamWriter;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URLEncoder;

import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CopyOfSendPostRequest {
    static String sessionId = "";

    public static void main(String[] args) throws Exception {
        
        //城市名称
        String city = URLEncoder.encode("重庆", "GB2312");
        System.out.println(city);
        // api url :北向URL
        String locationUrl = "http://php.weather.sina.com.cn/xml.php?city=" + city + "&password=DJOYnieT8234jlsK&day=0";

        // http body 消息体
        String reqBody = "";

        // http method
        String method = "POST";

        // http head : Content-Type 消息类型
        String contentType = "application/json;charset=UTF-8";

        // 设定连接的相关参数
        URL url = new URL(locationUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setReadTimeout(10000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", contentType);

        //写入请求消息体
        OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream(), "UTF-8");
        out.write(reqBody);
        out.flush();
        out.close();

        // 获取服务端的反馈
        String strLine = "";
        StringBuilder strResponse = new StringBuilder();
        try {
            Map<String, List<String>> rspHeaders = connection.getHeaderFields();

            Set<String> rspHeadNames = rspHeaders.keySet();
            for (String key : rspHeadNames) {
                //rspHeaders中的http状态码和描述的键为null
                if (null != key) {
                    strResponse.append(key + ": ");
                }
                strResponse.append(new String(rspHeaders.get(key).get(0)
                        .getBytes("iso-8859-1"), "UTF-8")
                        + "\n");
            }

            int code = connection.getResponseCode();
            // String status = connection.getResponseMessage();
            InputStream in;

            // 判断http状态码
            if (code == 200) {
                in = connection.getInputStream();
            } else {
                in = connection.getErrorStream();
            }
            if (null != in) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                while ((strLine = reader.readLine()) != null) {
                    strResponse.append("\n" + strLine);
                }
            }
            System.out.print(strResponse.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

 

posted on 2016-08-25 16:04  风灯  阅读(2634)  评论(0编辑  收藏  举报