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

java实现http的Post、Get、代理访问请求

程序员文章站 2024-03-08 20:26:52
本文实例讲解了java实现http的post、get、代理访问请求的详细代码片段,分享给大家供大家参考,具体内容如下 package com.snowfigure...

本文实例讲解了java实现http的post、get、代理访问请求的详细代码片段,分享给大家供大家参考,具体内容如下

package com.snowfigure.kits.net;
 
import java.io.bufferedreader; 
import java.io.ioexception;
import java.io.inputstream; 
import java.io.inputstreamreader; 
import java.io.outputstreamwriter;
import java.io.unsupportedencodingexception; 
import java.net.httpurlconnection; 
import java.net.inetsocketaddress;
import java.net.proxy;
import java.net.url; 
import java.net.urlconnection;
import java.util.list;
import java.util.map;
 
/** 
 * http请求工具类 
 * @author snowfigure 
 * @since 2014-8-24 13:30:56 
 * @version v1.0.1 
 */
public class httprequestutil {
  static boolean proxyset = false;
  static string proxyhost = "127.0.0.1";
  static int proxyport = 8087;
  /** 
   * 编码 
   * @param source 
   * @return 
   */ 
  public static string urlencode(string source,string encode) { 
    string result = source; 
    try { 
      result = java.net.urlencoder.encode(source,encode); 
    } catch (unsupportedencodingexception e) { 
      e.printstacktrace(); 
      return "0"; 
    } 
    return result; 
  }
  public static string urlencodegbk(string source) { 
    string result = source; 
    try { 
      result = java.net.urlencoder.encode(source,"gbk"); 
    } catch (unsupportedencodingexception e) { 
      e.printstacktrace(); 
      return "0"; 
    } 
    return result; 
  }
  /** 
   * 发起http请求获取返回结果 
   * @param req_url 请求地址 
   * @return 
   */ 
  public static string httprequest(string req_url) {
    stringbuffer buffer = new stringbuffer(); 
    try { 
      url url = new url(req_url); 
      httpurlconnection httpurlconn = (httpurlconnection) url.openconnection(); 
  
      httpurlconn.setdooutput(false); 
      httpurlconn.setdoinput(true); 
      httpurlconn.setusecaches(false); 
  
      httpurlconn.setrequestmethod("get"); 
      httpurlconn.connect(); 
  
      // 将返回的输入流转换成字符串 
      inputstream inputstream = httpurlconn.getinputstream(); 
      inputstreamreader inputstreamreader = new inputstreamreader(inputstream, "utf-8"); 
      bufferedreader bufferedreader = new bufferedreader(inputstreamreader); 
  
      string str = null; 
      while ((str = bufferedreader.readline()) != null) { 
        buffer.append(str); 
      } 
      bufferedreader.close(); 
      inputstreamreader.close(); 
      // 释放资源 
      inputstream.close(); 
      inputstream = null; 
      httpurlconn.disconnect(); 
  
    } catch (exception e) { 
      system.out.println(e.getstacktrace()); 
    } 
    return buffer.tostring(); 
  } 
    
  /** 
   * 发送http请求取得返回的输入流 
   * @param requesturl 请求地址 
   * @return inputstream 
   */ 
  public static inputstream httprequestio(string requesturl) { 
    inputstream inputstream = null; 
    try { 
      url url = new url(requesturl); 
      httpurlconnection httpurlconn = (httpurlconnection) url.openconnection(); 
      httpurlconn.setdoinput(true); 
      httpurlconn.setrequestmethod("get"); 
      httpurlconn.connect(); 
      // 获得返回的输入流 
      inputstream = httpurlconn.getinputstream(); 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
    return inputstream; 
  }
   
   
  /**
   * 向指定url发送get方法的请求
   * 
   * @param url
   *      发送请求的url
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @return url 所代表远程资源的响应结果
   */
  public static string sendget(string url, string param) {
    string result = "";
    bufferedreader in = null;
    try {
      string urlnamestring = url + "?" + param;
      url realurl = new url(urlnamestring);
      // 打开和url之间的连接
      urlconnection connection = realurl.openconnection();
      // 设置通用的请求属性
      connection.setrequestproperty("accept", "*/*");
      connection.setrequestproperty("connection", "keep-alive");
      connection.setrequestproperty("user-agent",
          "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
      // 建立实际的连接
      connection.connect();
      // 获取所有响应头字段
      map<string, list<string>> map = connection.getheaderfields();
      // 遍历所有的响应头字段
      for (string key : map.keyset()) {
        system.out.println(key + "--->" + map.get(key));
      }
      // 定义 bufferedreader输入流来读取url的响应
      in = new bufferedreader(new inputstreamreader(
          connection.getinputstream()));
      string line;
      while ((line = in.readline()) != null) {
        result += line;
      }
    } catch (exception e) {
      system.out.println("发送get请求出现异常!" + e);
      e.printstacktrace();
    }
    // 使用finally块来关闭输入流
    finally {
      try {
        if (in != null) {
          in.close();
        }
      } catch (exception e2) {
        e2.printstacktrace();
      }
    }
    return result;
  }
 
  /**
   * 向指定 url 发送post方法的请求
   * 
   * @param url
   *      发送请求的 url
   * @param param
   *      请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
   * @param isproxy
   *        是否使用代理模式
   * @return 所代表远程资源的响应结果
   */
  public static string sendpost(string url, string param,boolean isproxy) {
    outputstreamwriter out = null;
    bufferedreader in = null;
    string result = "";
    try {
      url realurl = new url(url);
      httpurlconnection conn = null;
      if(isproxy){//使用代理模式
        @suppresswarnings("static-access")
        proxy proxy = new proxy(proxy.type.direct.http, new inetsocketaddress(proxyhost, proxyport));
        conn = (httpurlconnection) realurl.openconnection(proxy);
      }else{
        conn = (httpurlconnection) realurl.openconnection();
      }
      // 打开和url之间的连接
       
      // 发送post请求必须设置如下两行
      conn.setdooutput(true);
      conn.setdoinput(true);
      conn.setrequestmethod("post");  // post方法
       
       
      // 设置通用的请求属性
       
      conn.setrequestproperty("accept", "*/*");
      conn.setrequestproperty("connection", "keep-alive");
      conn.setrequestproperty("user-agent",
          "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1;sv1)");
      conn.setrequestproperty("content-type", "application/x-www-form-urlencoded");
       
      conn.connect();
       
      // 获取urlconnection对象对应的输出流
      out = new outputstreamwriter(conn.getoutputstream(), "utf-8");
      // 发送请求参数
      out.write(param);
      // flush输出流的缓冲
      out.flush();
      // 定义bufferedreader输入流来读取url的响应
      in = new bufferedreader(
          new inputstreamreader(conn.getinputstream()));
      string line;
      while ((line = in.readline()) != null) {
        result += line;
      }
    } catch (exception e) {
      system.out.println("发送 post 请求出现异常!"+e);
      e.printstacktrace();
    }
    //使用finally块来关闭输出流、输入流
    finally{
      try{
        if(out!=null){
          out.close();
        }
        if(in!=null){
          in.close();
        }
      }
      catch(ioexception ex){
        ex.printstacktrace();
      }
    }
    return result;
  }  
   
  public static void main(string[] args) {
    //demo:代理访问
    string url = "http://api.adf.ly/api.php";
    string para = "key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
     
    string sr=httprequestutil.sendpost(url,para,true);
    system.out.println(sr);
  }
   
}

希望本文所述对大家学习java程序设计有所帮助。