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 ...
随机推荐
- 垃圾收集器之:G1收集器
G1垃圾收集器是一种工作在堆内不同分区上的并发收集器.分区既可以归属于老年代,也可以归属新生代,同一个代的分区不需要保持连续.为老年代设计分区的初衷是我们发现并发后台线程在回收老年代中没有引用的对象时 ...
- 查找占用CPU高线程
1.根据进程号查看线程 ps -mp pid -o THREAD,tid,time 2 把tid值转成16进制 printf "%x\n" tid 3.根据上面获取到的16进制数据 ...
- ORM创建 脚本运行
- [Python] Hermite 插值
# -*- coding: utf-8 -*- #Program 0.5 Hermite Interpolation import matplotlib.pyplot as plt import nu ...
- selenium+python自动化90-unittest多线程执行用例
前言 假设执行一条脚本(.py)用例一分钟,那么100个脚本需要100分钟,当你的用例达到一千条时需要1000分钟,也就是16个多小时... 那么如何并行运行多个.py的脚本,节省时间呢?这就用到多线 ...
- uva-10160-枚举
若当前搜索到的城市n前面1-n-1编号的城市中有没有通电的,则永远也无法输送电力给那个城市,因为在剪枝时附加了和此结点连接的最大结点小于当前的结点 这段 for(int i = 1; i < c ...
- redis删除key
shell命令如下 #!/bin/bash echo "$(redis-cli keys "_query*")" | while read LINE; do e ...
- 7.css实现三角形
1.效果: 2.代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...
- OpenCL 图像卷积 3 使用 CPU
▶ CPU 图像卷积,共四种方法.分别为基本串行,使用模板,使用局部内存,使用AVX指令优化 ● 全部的代码,仅在主函数中选择调用的函数名即可. #include <stdio.h> #i ...
- 面向过程中的局部变量(global)
1.school = 'oldboy.edu' def change_name(name): school = " Mage Linux" # 局 ...