使用Java发送这两种请求的代码大同小异,只是一些参数设置的不同。步骤如下:

通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
设置请求的参数
发送请求
以输入流的形式获取返回内容
关闭输入流

Get

package com.test.httprequestdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; public class HttpGetRequest { /**
* Main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(doGet());
} /**
* Get Request
* @return
* @throws Exception
*/
public static String doGet() throws Exception {
URL localURL = new URL("http://localhost:8080/test/");
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null; if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} try {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
} } finally { if (reader != null) {
reader.close();
} if (inputStreamReader != null) {
inputStreamReader.close();
} if (inputStream != null) {
inputStream.close();
} } return resultBuffer.toString();
} }

Post

package com.test.httprequestdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; public class HttpPostRequest { /**
* Main
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(doPost());
} /**
* Post Request
* @return
* @throws Exception
*/
public static String doPost() throws Exception {
String parameterData = "username=test"; URL localURL = new URL("http://localhost:8080/test/");
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length())); OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null; try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush(); if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
} } finally { if (outputStreamWriter != null) {
outputStreamWriter.close();
} if (outputStream != null) {
outputStream.close();
} if (reader != null) {
reader.close();
} if (inputStreamReader != null) {
inputStreamReader.close();
} if (inputStream != null) {
inputStream.close();
} } return resultBuffer.toString();
} }

封装好的案例

package com.test.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map; import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class HttpRequestor {
private static final Logger logger = Logger.getLogger(HttpRequestor.class); public static void main(String[] args) throws Exception {
} private static Integer connectTimeout = null;
private static Integer socketTimeout = null;
private static String proxyHost = null;
private static Integer proxyPort = null; /**
* Do GET request
* @param url
* @param charset:(默认)utf-8
* @param contentType:(默认)application/x-www-form-urlencoded
* @return
* @throws Exception
* @throws IOException
*/
public static String doGet(String url,String charset,String contentType) {
if(StringUtils.isBlank(url)) return null;
if(StringUtils.isBlank(charset)) charset="utf-8";
if(StringUtils.isBlank(contentType)) contentType = "application/x-www-form-urlencoded";
logger.info("-------start-------request.get.http:"+url); InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type",contentType);
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally { if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} } logger.info("------end--------request.get");
return resultBuffer.toString();
} /**
* Do POST request
* @param url
* @param parameterMap
* @param charset:(默认)utf-8
* @param contentType:(默认)application/x-www-form-urlencoded
* @return
* @throws Exception
*/
public static String doPost(String url, Map<String,String> parameterMap,String charset,String contentType) {
if(StringUtils.isBlank(charset)) charset="utf-8";
if(StringUtils.isBlank(contentType)) contentType = "application/x-www-form-urlencoded";
logger.info("-------start-------request.post.http:"+url+"?"+parameterMap.toString()); StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator<String> iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = iterator.next();
value = parameterMap.get(key);
parameterBuffer.append(key).append("=").append(value==null?"":value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
} OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
URL localURL = new URL(url);
URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush(); if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader); while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} catch (Exception e) {
e.printStackTrace(); } finally { if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} } logger.info("------end--------request.post");
return resultBuffer.toString();
} private static URLConnection openConnection(URL localURL) throws IOException {
URLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
connection = localURL.openConnection(proxy);
} else {
connection = localURL.openConnection();
}
renderRequest(connection);
return connection;
} /**
* Render request according setting
* @param request
*/
private static void renderRequest(URLConnection connection) { if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
} if (socketTimeout != null) {
connection.setReadTimeout(socketTimeout);
} } /*
* Getter & Setter
*/
public Integer getConnectTimeout() {
return connectTimeout;
} public void setConnectTimeout(Integer connectTimeout) {
HttpRequestor.connectTimeout = connectTimeout;
} public Integer getSocketTimeout() {
return socketTimeout;
} public void setSocketTimeout(Integer socketTimeout) {
HttpRequestor.socketTimeout = socketTimeout;
} public String getProxyHost() {
return proxyHost;
} public void setProxyHost(String proxyHost) {
HttpRequestor.proxyHost = proxyHost;
} public Integer getProxyPort() {
return proxyPort;
} public void setProxyPort(Integer proxyPort) {
HttpRequestor.proxyPort = proxyPort;
} }

java.net.URLConnectioin的http(get,post)请求(原生)的更多相关文章

  1. [Java] 模拟HTTP的Get和Post请求

    在之前,写了篇Java模拟HTTP的Get和Post请求的文章,这篇文章起源与和一个朋友砍飞信诈骗网站的问题,于是动用了Apache的comments-net包,也实现了get和post的http请求 ...

  2. 通过java.net.URLConnection发送HTTP请求(原生、爬虫)

    目录 1. 运用原生Java Api发送简单的Get请求.Post请求 2. 简单封装 3. 简单测试 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求.Ja ...

  3. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

  4. 【Java Web开发学习】跨域请求

    [Java Web开发学习]跨域请求 ================================================= 1.使用jsonp ===================== ...

  5. Java生鲜电商平台-SpringCloud分布式请求跟踪系统设计与实践

    Java生鲜电商平台-SpringCloud分布式请求跟踪系统设计与实践 Java生鲜电商平台微服务现状 某个服务挂了,导致上游大量报警,如何快速定位哪个服务出问题? 某个核心挂了,导致大量报错,如何 ...

  6. MySQL_(Java)使用JDBC向数据库发起查询请求

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC创建用户名和密码校验查询方法 传送门 MySQL_(Java)使用preparestatement ...

  7. AJAX的get和post请求原生编写方法

    var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.stat ...

  8. java发送http的get、post请求

    转载博客:http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html Http请求类 package wzh.Http; impor ...

  9. java发送http的get、post请求[转]

    原文链接:http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html package wzh.Http; import java.i ...

随机推荐

  1. 小机房的树 codevs 2370

    2370 小机房的树  时间限制: 1 s  空间限制: 256000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 Description 小机房有棵焕狗种的树 ...

  2. jvm虚拟机性能监控与故障处理工具

    java开发人员肯定知道jdk的bin目录中有java.exe javac.exe这两个命令行工具,但并非所有程序员都了解过jdk的bin目录之中其他命令行的作用.jdk的工具,体积都比较小,这些命令 ...

  3. [No000055]教你早晨清肠、除口臭、色斑、大肚腩

    [长生不老的秘诀] 释.道.医三家有个共同的秘诀:"要叫人不死. 肠中须无屎". 佛家除要求人们戒杀吃素外,还认为早饭是天食,中饭是人食,晚饭是鬼食. 因此,为了身体健康,不妨碍修 ...

  4. ThreadLocal用法和实现原理

    如果你定义了一个单实例的java bean,它有若干属性,但是有一个属性不是线程安全的,比如说HashMap.并且碰巧你并不需要在不同的线程中共享这个属性,也就是说这个属性不存在跨线程的意义.那么你不 ...

  5. Zygote进程【1】——Zygote的诞生

    在Android中存在着C和Java两个完全不同的世界,前者直接建立在Linux的基础上,后者直接建立在JVM的基础上.zygote的中文名字为"受精卵",这个名字很好的诠释了zy ...

  6. npm换源

    作者一介布衣:http://yijiebuyi.com/blog/b12eac891cdc5f0dff127ae18dc386d4.html npm 是node.js 环境下的包管理器,非常强大智能. ...

  7. Java数据类型和变量

    Java中存在2种数据类型,下面我们来详解一下: 基本数据类型: 引用数据类型: 可以用一张表来记录: 基本数据类型 整型 byte:1个字节8位,取值范围为:[-128, 127],直接写值:(by ...

  8. c#socket编程基础

    Microsoft.Net Framework为应用程序访问Internet提供了分层的.可扩展的以及受管辖的网络服务,其名字空间System.Net和System.Net.Sockets包含丰富的类 ...

  9. [数据库]漫谈ElasticSearch关于ES性能调优几件必须知道的事(转)

    ElasticSearch是现在技术前沿的大数据引擎,常见的组合有ES+Logstash+Kibana作为一套成熟的日志系统,其中Logstash是ETL工具,Kibana是数据分析展示平台.ES让人 ...

  10. Kafka是分布式发布-订阅消息系统

    Kafka是分布式发布-订阅消息系统 https://www.biaodianfu.com/kafka.html Kafka是分布式发布-订阅消息系统.它最初由LinkedIn公司开发,之后成为Apa ...