Java HttpURLConnection使用方法详解

本文实例为大家分享了Java HttpURLConnection使用,供大家参考,具体内容如下

包括使用HttpURLConnection执行get/post请求

package com.cn.testproject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class httpconnectionUrlDemo {
  public static void main(String[] args) throws Exception {
    //get();
    post();
  }

 

  public static void get() throws Exception {
    String path = "http://www.baidu.com";
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    byte[] data = toByteArray(inStream);
    String result = new String(data,"UTF-8");
    System.out.println(result);
  }

 

  public static void post() throws Exception {
    String encoding = "UTF-8";
    //post的form参数(json兼职对)
    String params = "[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
    String path = "http://www.baidu.com";
    byte[] data = params.getBytes(encoding);
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
   
    conn.setRequestProperty("Content-Type","application/x-javascript; charset=" + encoding);
    conn.setRequestProperty("Content-Length",String.valueOf(data.length));
    conn.setConnectTimeout(5 * 1000);
    OutputStream outStream = conn.getoutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();
    System.out.println(conn.getResponseCode()); // 响应代码 200表示成功
    if (conn.getResponseCode() == 200) {
      InputStream inStream = conn.getInputStream();
      String result = new String(toByteArray(inStream),"UTF-8");
      System.out.println(result); // 响应代码 200表示成功
    }
  }
  private static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
      output.write(buffer,n);
    }
    return output.toByteArray();
  }
}

GitHub:https://github.com/taz372436

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...