欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java HttpURLConnection使用方法详解

程序员文章站 2024-04-02 08:34:10
本文实例为大家分享了java httpurlconnection使用,供大家参考,具体内容如下 包括使用httpurlconnection执行get/post请求...

本文实例为大家分享了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:

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