码迷,mamicode.com
首页 > Web开发 > 详细

HttpURLConnection读取http信息

时间:2015-11-17 15:20:39      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

废话不多说,直接上code.

package mytest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.io.InputStream;

public class MainEntry {

    public static void main(String[] args) throws Exception {
        String urlStr = "http://passport.cnblogs.com/user/signin";
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        
        StringBuffer params = new StringBuffer();
        params.append("input1")
              .append("=")
              .append("lucas.shanghai")
              .append("&")
              .append("input2")
              .append("=")
              .append("abc");
        
        byte[] bytes = params.toString().getBytes();
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params.toString());
        printWriter.flush();
        
        Map headers = conn.getHeaderFields();
        Set<String> keys = headers.keySet();
        
        for(String key : keys)
        {
            System.out.println(key + ": " + conn.getHeaderField(key));
        }
        
        int responseCode = conn.getResponseCode();
        
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = "";
        
        StringBuffer responseResult = new StringBuffer();
        while((line = bufferedReader.readLine()) != null) {
            responseResult.append("/n").append(line);
        }
        
        System.out.println(responseResult.toString());
    }
}

 

HttpURLConnection读取http信息

标签:

原文地址:http://www.cnblogs.com/devtesters/p/4971792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!