使用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. AC日记——鬼谷子的钱袋 codevs 2998

    2998 鬼谷子的钱袋 2006年省队选拔赛湖南  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 大师 Master    题目描述 Description 鬼谷子非常聪明,正 ...

  2. dotNet开发游戏微端

    需求分析 功能要求 当玩家使用不支持 unity webplayer 的浏览器进入游戏时,让玩家通过微端玩游戏. 确保微端的功能和页游戏功能一致. 大体功能就是为unity web game开发微端, ...

  3. [转]关于vs调试正确。但是发布到iis就出现无法访问后天局面

    最近使用extjs+ashx进行ajax请求过程操作的时候发现一个问题..当我把程序发布到iis的时候就出现一只不执行到success回调函数. 当弹出状态值一看尽然是500.我就纳闷了.又没有语法错 ...

  4. Linux常用命令学习

    1.ls命令 就是list的缩写,通过ls 命令不仅可以查看linux文件夹包含的文件,而且可以查看文件权限(包括目录.文件夹.文件权限)查看目录信息等等 常用参数搭配: ls -a 列出目录所有文 ...

  5. preg_match()漏洞

    今天大哥丢了一道题过来. <?php $str = intval($_GET['id']); $reg = preg_match('/\d/is', $_GET['id']); //有0-9的数 ...

  6. Android爬坑之旅:软键盘挡住输入框问题的终极解决方案

    前言 开发做得久了,总免不了会遇到各种坑.而在Android开发的路上,『软键盘挡住了输入框』这个坑,可谓是一个旷日持久的巨坑--来来来,我们慢慢看. 入门篇 Base 最基本的情况,如图所示:在页面 ...

  7. sublime text2 配置代码对齐快捷键

    menu under Preferences → Key Bindings – User [{"keys": ["ctrl+shift+r"], "c ...

  8. 部署Linux下的man慢查询中文帮助手册环境

    对于Linux运维工作者来说,man查询手册绝对是一个好东西.当我们对一些命令或参数有些许模糊时,可以通过man查询手册来寻求帮助.其实Linux之所以强大, 就在于其强大的命令行, 面对如此繁杂的命 ...

  9. 十个节省时间的MySQL命令

    十个节省时间的MySQL命令 2011-02-23 16:07 黄永兵 译 IT168 字号:T | T 编者在工作中积累起来了一些MySQL命令行客户端技巧,这些技巧或多或少会帮助您节省大量的时间. ...

  10. java多线程系类:基础篇:09之interrupt()和线程终止方式

    概要 本章,会对线程的interrupt()中断和终止方式进行介绍.涉及到的内容包括:1. interrupt()说明2. 终止线程的方式2.1 终止处于"阻塞状态"的线程2.2 ...