用户工具

站点工具


开发:java:httpurlconnection

HttpURLConnection简介

HttpURLConnection继承了URLConnection,所以在URLConnection的基础上进一步改进,增加了一些用于操作HTTP资源的便捷方法。Java中HttpURLConnection对象通过URL.openConnection()方法来获得,需要进行强制转换。先来介绍几个HttpURLConnection的常用方法:

  • void setConnectTimeout(int timeout):设置连接超时时长,如果超过timeout时长,则放弃连接,单位以毫秒计算。
  • void setDoInput(boolean newValue) :标志是否允许输入。
  • void setDoOutput(boolean newValue):标志是否允许输出。
  • String getRequestMethod():获取发送请求的方法。
  • int getResponseCode():获取服务器的响应码。
  • void setRequestMethod(String method):设置发送请求的方法。
  • void setRequestProperty(String field,String newValue):设置请求报文头,并且只对当前HttpURLConnection有效。

GET方式

这个例子通过GET方式从服务端获取一张图片的信息,并把其保存在本地磁盘中。服务器为本机上的IIS,一张静态图片,直接通过URL访问。

直接上Java代码,注释已经解释的很清楚了。

package com.http.get;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
public class HttpUtils {
    private static String URL_PATH = "http://192.168.1.106:8080/green.jpg";
    /**
     * @param args
     */
    public static void main(String[] args) {
        // 调用方法获取图片并保存
        saveImageToDisk();
    }
    /**
     * 通过URL_PATH的地址访问图片并保存到本地
     */
    public static void saveImageToDisk()
    {
        InputStream inputStream= getInputStream();
        byte[] data=new byte[1024];
        int len=0;
        FileOutputStream fileOutputStream=null;
        try {
            //把图片文件保存在本地F盘下
            fileOutputStream=new FileOutputStream("F:\\test.png");
            while((len=inputStream.read(data))!=-1) 
            {
                //向本地文件中写入图片流
                fileOutputStream.write(data,0,len);                
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            //最后关闭流
            if(inputStream!=null)
            {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null)
            {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 通过URL获取图片
     * @return URL地址图片的输入流。
     */
    public static InputStream getInputStream() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
 
        try {
            //根据URL地址实例化一个URL对象,用于创建HttpURLConnection对象。
            URL url = new URL(URL_PATH);
 
            if (url != null) {
                //openConnection获得当前URL的连接
                httpURLConnection = (HttpURLConnection) url.openConnection();
                //设置3秒的响应超时
                httpURLConnection.setConnectTimeout(3000);
                //设置允许输入
                httpURLConnection.setDoInput(true);
                //设置为GET方式请求数据
                httpURLConnection.setRequestMethod("GET");
                //获取连接响应码,200为成功,如果为其他,均表示有问题
                int responseCode=httpURLConnection.getResponseCode();
                if(responseCode==200)
                {
                    //getInputStream获取服务端返回的数据流。
                    inputStream=httpURLConnection.getInputStream();
                }
            }
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }
 
}

POST方式

这个例子通过POST方式访问一个登陆页面,需要输入用户名(username)和密码(password)。虽然这里使用的Java在讲解问题,但是服务端是使用.Net的框架,一个很简单的HTML页面加一个表单传送的一般处理程序,输入为admin+123为登陆成功,这里不累述了。

package com.http.post;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
 
public class postUtils {
 
    private static String PATH = "http://192.168.222.1:1231/loginas.ashx";
    private static URL url;
 
    public postUtils() {
    }
    static {
        try {
            url = new URL(PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 通过给定的请求参数和编码格式,获取服务器返回的数据
     * @param params 请求参数
     * @param encode 编码格式
     * @return 获得的字符串
     */
    public static String sendPostMessage(Map<String, String> params,
            String encode) {
        StringBuffer buffer = new StringBuffer();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    buffer.append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");//请求的参数之间使用&分割。
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
 
            }
            buffer.deleteCharAt(buffer.length() - 1);
            System.out.println(buffer.toString());
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.setConnectTimeout(3000);
                //设置允许输入输出
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                byte[] mydata = buffer.toString().getBytes();
                //设置请求报文头,设定请求数据类型
                urlConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                //设置请求数据长度
                urlConnection.setRequestProperty("Content-Length",
                        String.valueOf(mydata.length));
                //设置POST方式请求数据
                urlConnection.setRequestMethod("POST");
                OutputStream outputStream = urlConnection.getOutputStream();
                outputStream.write(mydata);
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == 200) {
                    return changeInputStream(urlConnection.getInputStream(),
                            encode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
 
    /**
     * 把服务端返回的输入流转换成字符串格式
     * @param inputStream 服务器返回的输入流
     * @param encode 编码格式
     * @return 解析后的字符串
     */
    private static String changeInputStream(InputStream inputStream,
            String encode) { 
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result="";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data,0,len);                    
                }
                result=new String(outputStream.toByteArray(),encode);
 
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        //通过Map设置请求字符串。
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", "admin");
        params.put("password", "123");        
        String result=sendPostMessage(params, "utf-8");
        System.out.println(result);
    }
 
}

链接

开发/java/httpurlconnection.txt · 最后更改: 2015-01-12 17:14 由 danding

粤ICP备16007019号-3