Java HttpURLConnection使用方法详解

作者:kgmucom   在线用户:8
风之恋奇迹私服技术网是一家提供最新互联网编程技术网站

HttpURLConnection类是很抽象的,这表示应用程序和URL之间的通信连接,下面是爱站技术频道小编给大家分享的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, 0, n);
    }
    return output.toByteArray();
  }
}

GitHub:https://github.com/taz372436

以上就是爱站技术频道小编给大家带来的Java HttpURLConnection使用方法详解,希望篇文章能帮助到大家,想要学到更多专业资讯请继续关注js.aizhan.com吧!

提供最全面的奇迹sf开服版本和最新的奇迹私服开服技术信息,奇迹私服文库让每一位奇迹私服玩家找到自己需要的版本技术文章

上一篇:浅析java变量的区别

下一篇:Java中消息队列任务的平滑关闭详解

请发表您的评论