Java发送http请求并为http设置头信息

  1. import java.io.BufferedReader;  
  2. import java.io.DataOutputStream;  
  3. import java.io.InputStreamReader;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.InetAddress;  
  6. import java.net.URL;  
  7. import java.net.UnknownHostException;  
  8.   
  9. public class createHttp {  
  10.   
  11.     public static final String GET_URL = "http://192.168.31.5/mall-back/if_user/store_list?storeId=32";  
[java] view plain copy
  1. // 测试接口  
  2. public static final String POST_URL = "http://192.168.31.230:8180/mdserver/service/installLock";  
  3.      
  4.    /** 
  5.     * 接口调用 GET 
  6.     */  
  7. public static void httpURLConectionGET() {  
  8.        try {  
  9.            URL url = new URL(GET_URL);    //把字符串转换为URL请求地址  
  10.            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接  
  11.            //addRequestProperty添加相同的key不会覆盖,如果相同,内容会以{name1,name2}  
  12.            connection.addRequestProperty("from""sfzh");  //来源哪个系统  
  13.            //setRequestProperty添加相同的key会覆盖value信息  
  14.            //setRequestProperty方法,如果key存在,则覆盖;不存在,直接添加。  
  15.            //addRequestProperty方法,不管key存在不存在,直接添加。  
  16.            connection.setRequestProperty("user""user");  //访问申请用户  
  17.            InetAddress address = InetAddress.getLocalHost();   
  18.         String ip=address.getHostAddress();//获得本机IP  
  19.            connection.setRequestProperty("ip",ip);  //请求来源IP  
  20.            connection.setRequestProperty("encry""00000");  
  21.            connection.connect();// 连接会话  
  22.            // 获取输入流  
  23.            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));  
  24.            String line;  
  25.            StringBuilder sb = new StringBuilder();  
  26.            while ((line = br.readLine()) != null) {// 循环读取流  
  27.                sb.append(line);  
  28.            }  
  29.            br.close();// 关闭流  
  30.            connection.disconnect();// 断开连接  
  31.            System.out.println(sb.toString());  
  32.        } catch (Exception e) {  
  33.            e.printStackTrace();  
  34.            System.out.println("失败!");  
  35.        }  
  36.    }  
  37.      
  38.    /** 
  39.     * 接口调用  POST 
  40.     */  
  41.    public static void httpURLConnectionPOST () {  
  42.        try {  
  43.         //传递参数  
  44.         String Parma = "?cardType={}&cardID={}";  
  45.           
  46.            URL url = new URL(POST_URL);  
  47.            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
  48.            // 此时cnnection只是为一个连接对象,待连接中  
  49.            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  50.            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
  51.            connection.setDoOutput(true);  
  52.            // 设置连接输入流为true  
  53.            connection.setDoInput(true);  
  54.            // 设置请求方式为post  
  55.            connection.setRequestMethod("POST");  
  56.            // post请求缓存设为false  
  57.            connection.setUseCaches(false);  
  58.            // 设置该HttpURLConnection实例是否自动执行重定向  
  59.            connection.setInstanceFollowRedirects(true);  
  60.            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
  61.            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
  62.            // ;charset=utf-8 必须要,不然妙兜那边会出现乱码【★★★★★】  
  63.            //addRequestProperty添加相同的key不会覆盖,如果相同,内容会以{name1,name2}  
  64.            connection.addRequestProperty("from""sfzh");  //来源哪个系统  
  65.            //setRequestProperty添加相同的key会覆盖value信息  
  66.            //setRequestProperty方法,如果key存在,则覆盖;不存在,直接添加。  
  67.            //addRequestProperty方法,不管key存在不存在,直接添加。  
  68.            connection.setRequestProperty("user""user");  //访问申请用户  
  69.            InetAddress address = InetAddress.getLocalHost();   
  70.         String ip=address.getHostAddress();//获得本机IP  
  71.            connection.setRequestProperty("ip",ip);  //请求来源IP  
  72.            connection.setRequestProperty("encry""123456");  
  73.            connection.setRequestProperty("Content-Type""application/x-www-form-urlencoded;charset=utf-8");      
  74.            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
  75.            connection.connect();  
  76.            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
  77.            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
  78.            // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444  
  79.            String parm ="username=zhagnsan&password=0000";  
  80.            System.out.println("传递参数:"+parm);  
  81.            // 将参数输出到连接  
  82.            dataout.writeBytes(parm);  
  83.            // 输出完成后刷新并关闭流  
  84.            dataout.flush();  
  85.            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
  86.            //System.out.println(connection.getResponseCode());  
  87.            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
  88.            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
  89.            String line;  
  90.            StringBuilder sb = new StringBuilder(); // 用来存储响应数据  
  91.              
  92.            // 循环读取流,若不到结尾处  
  93.            while ((line = bf.readLine()) != null) {  
  94.             //sb.append(bf.readLine());  
  95.             sb.append(line).append(System.getProperty("line.separator"));  
  96.            }  
  97.            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)   
  98.            connection.disconnect(); // 销毁连接  
  99.            System.out.println(sb.toString());  
  100.        } catch (Exception e) {  
  101.            e.printStackTrace();  
  102.        }  
  103.    }  
  104.      
  105.    public static void main(String[] args) throws UnknownHostException {  
  106.     httpURLConectionGET();  
  107.          //httpURLConnectionPOST();  
  108.    }  
展开阅读全文

没有更多推荐了,返回首页