Url,HTTPUrlConnection(一)
package com.cmy.urlcon; 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.util.HashMap;
import java.util.Iterator;
import java.util.Map; public class HttpRequestor { private String charset = "utf-8";
private Integer connectTimeout = null;
private Integer socketTimeout = null;
private String proxyHost = null;
private Integer proxyPort = null; public String doGet(String urlPath) throws Exception { URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded"); InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bfReader = null;
StringBuffer sb = new StringBuffer();
String readLine = null; if (connection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is failue, Response code is "
+ connection.getResponseCode());
} try {
inputStream = connection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bfReader = new BufferedReader(inputStreamReader);
while ((readLine = bfReader.readLine()) != null) {
sb.append(readLine);
} } catch (Exception e) {
e.printStackTrace();
} finally {
bfReader.close();
inputStreamReader.close();
inputStream.close();
} return sb.toString(); } public static String doPost(String urlPath, Map paramMap) throws Exception {
URL url = new URL(urlPath);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuffer paramBuffer = new StringBuffer(); if (paramMap != null) {
Iterator iterator = paramMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next(); if ((value = (String) paramMap.get(key)) != null) {
paramBuffer.append(value);
} else {
value = "";
}
paramBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
paramBuffer.append("&");
}
}
}
System.out.println("POST parameter: " + paramBuffer.toString()); con.setRequestProperty("Accept-Charset", "utf-8");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setConnectTimeout(3000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
String cookie0 = con.getHeaderField("Set-Cookie"); OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bfReader = null;
StringBuffer sb = new StringBuffer();
String readLine = null; try {
outputStream = con.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(paramBuffer.toString());
outputStreamWriter.flush(); } catch (Exception e) {
e.printStackTrace();
} if (con.getResponseCode() >= 300) {
throw new Exception("HTTP Request is failue, Response code is "
+ con.getResponseCode());
} try {
inputStream = con.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bfReader = new BufferedReader(inputStreamReader);
while ((readLine = bfReader.readLine()) != null) {
sb.append(readLine);
} } catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
outputStream.close();
bfReader.close();
inputStreamReader.close();
inputStream.close();
} return sb.toString();
} private HttpURLConnection openConnection(URL localURL) throws IOException {
HttpURLConnection connection;
if (proxyHost != null && proxyPort != null) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
connection = (HttpURLConnection) localURL.openConnection(proxy);
} else {
connection = (HttpURLConnection) localURL.openConnection();
}
return connection;
} private void renderRequest(HttpURLConnection connection) { if (connectTimeout != null) {
connection.setConnectTimeout(connectTimeout);
} if (socketTimeout != null) {
connection.setReadTimeout(socketTimeout);
} } public String getCharset() {
return charset;
} public void setCharset(String charset) {
this.charset = charset;
} public Integer getConnectTimeout() {
return connectTimeout;
} public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
} public Integer getSocketTimeout() {
return socketTimeout;
} public void setSocketTimeout(Integer socketTimeout) {
this.socketTimeout = socketTimeout;
} public String getProxyHost() {
return proxyHost;
} public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
} public Integer getProxyPort() {
return proxyPort;
} public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
} /**
* test case
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
/* Post Request */
Map dataMap = new HashMap();
dataMap.put("username", "Nick Huang");
dataMap.put("blog", "IT");
System.out.println(new HttpRequestor().doPost("http://localhost:8080/OneHttpServer/", dataMap)); /* Get Request */
System.out.println(new HttpRequestor().doGet("http://localhost:8080/OneHttpServer/")); } }
http://www.runoob.com/java/java-url-processing.html
Url,HTTPUrlConnection(一)的更多相关文章
- 使用Java的URL/HttpURLConnection进行远程调用(POST请求)
利用Java的HttpURLConnection进行远程url请求(调用远程接口) 测试类:请求类型为json,以post方式请求,利用OutputStream写入数据 实体类: public cla ...
- [02] URL和HttpURLConnection类
1.URL的概念 统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址. URL的基本格式是: <METHOD&g ...
- HttpUrlConnection 基础使用
From https://developer.android.com/reference/java/net/HttpURLConnection.html HttpUrlConnection: A UR ...
- Android利用HttpURLConnection实现模拟登录
最近在做一个APP,需要模拟登录教务处,之前曾经用HttpClient做过,点这里,但是发现最新的Android SDK已经不支持Httpclient了,所以只好在琢磨一下HttpURLConnect ...
- 利用HttpURLConnection发送请求
HttpURLConnection: 每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConne ...
- 传入url地址请求服务器api,浏览器显示图片
@RequestMapping("/proxyImage") public void proxyImage(HttpServletRequest request, HttpServ ...
- Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端
Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端 本博客前面博文中利用org.apache.http包中API进行Android客户端HTTP连接的例子 ...
- [Android] HttpURLConnection & HttpClient & Socket
Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...
- Android通过HttpURLConnection链接到网络,并获取网络数据
1.判断网络是否连接 private void networkIsconnected(String str){ ConnectivityManager connMgr = (ConnectivityM ...
随机推荐
- 杂项:TCL
ylbtech-杂项:TCL TCL,工具命令语言(Tool Command Language)是一门有编程特征的解释语言,可在 Unix.Windows 和 Apple Macintosh 操作系统 ...
- [C#]反射遍历对象属性
/// <summary> /// C#反射遍历对象属性 /// </summary> /// <typeparam name="T">对象类型 ...
- 使用postman模拟appium的http请求
Appium是Server,接收http请求,使用Postman模拟请求 1.anyproxy 1.1.安装和运行 #安装 npm i -g anyproxy # 运行anyproxy,端口默认800 ...
- 针对ROS5版本的配置导出和导入(迁移其他服务器)
1.在老ROS,导出当前系统配置export compact RouterOS 5.12 新增功能 export compact 命令,该命令简化了导出的参数,仅导出修改的配置,系统默 认配置参数将不 ...
- [UE4]UE4中的常见类
一.Actor:可以放在世界中物体 二.Pawn:可以接受Controller输入的Actor 三.Character:是一个可以行走.跑.跳等行为的Pawn 四.Controller:没有物理表现的 ...
- EC20 MODULE serial com log in passwd
ec20 module would print debug info via debug uart, and you can log in by user root, the passwd is qu ...
- 【BZOJ】4517 [Sdoi2016]排列计数(数学+错排公式)
题目 传送门:QWQ 分析 $ O(nlogn) $预处理出阶乘和阶乘的逆元,然后求组合数就成了$O(1)$了. 最后再套上错排公式:$ \huge d[i]=(i-1) \times (d[i-1] ...
- SQL Server 2008 CDC增量变更捕获详解
1 背景: 随着公司业务的成长,数据量也随之的不断增长.随之而来的问题是在做ETL的时候,时间花费也越来越长.为了节省时间开销,我们只想要更新最新的数据,不想要把公司历年所有的数据都进行处理.这种情况 ...
- 【Python编程:从入门到实践】chapter8 函数
chapter8 函数 8.6 将函数存储在模块中 8.6.1 导入整个模块 要让函数是可导入的,的先创建模块.模块 的扩展名为.py的文件 import pizza 8.6.2 到导入特定的函数 f ...
- mysql级联删除
一个building对应多个rooms,building删除----级联删除相关的rooms 第一步, 创建buildings表,如下创建语句: USE testdb; CREATE TABLE bu ...