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(一)的更多相关文章

  1. 使用Java的URL/HttpURLConnection进行远程调用(POST请求)

    利用Java的HttpURLConnection进行远程url请求(调用远程接口) 测试类:请求类型为json,以post方式请求,利用OutputStream写入数据 实体类: public cla ...

  2. [02] URL和HttpURLConnection类

    1.URL的概念 统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址. URL的基本格式是: <METHOD&g ...

  3. HttpUrlConnection 基础使用

    From https://developer.android.com/reference/java/net/HttpURLConnection.html HttpUrlConnection: A UR ...

  4. Android利用HttpURLConnection实现模拟登录

    最近在做一个APP,需要模拟登录教务处,之前曾经用HttpClient做过,点这里,但是发现最新的Android SDK已经不支持Httpclient了,所以只好在琢磨一下HttpURLConnect ...

  5. 利用HttpURLConnection发送请求

    HttpURLConnection: 每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConne ...

  6. 传入url地址请求服务器api,浏览器显示图片

    @RequestMapping("/proxyImage") public void proxyImage(HttpServletRequest request, HttpServ ...

  7. Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端

    Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端 本博客前面博文中利用org.apache.http包中API进行Android客户端HTTP连接的例子 ...

  8. [Android] HttpURLConnection & HttpClient & Socket

    Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...

  9. Android通过HttpURLConnection链接到网络,并获取网络数据

    1.判断网络是否连接 private void networkIsconnected(String str){ ConnectivityManager connMgr = (ConnectivityM ...

随机推荐

  1. 分布式一致性协议之:Raft算法

    一致性算法Raft详解 背景 熟悉或了解分布性系统的开发者都知道一致性算法的重要性,Paxos一致性算法从90年提出到现在已经有二十几年了,而Paxos流程太过于繁杂实现起来也比较复杂,可能也是以为过 ...

  2. shell脚本判断语句和循环语句

    if判断语句 exit跳出判读语句 不加exit的结果 read -n(不换行) 判断是否输入的是数字 read age[[ $age =~ ^[0-9]+$ ]]if [ $? -ne 0 ]; t ...

  3. [UE4]事件处理(Handling Events)和委托(Delegate)代码示例(一)

    1. 通过重写虚函数来处理事件 MyTriggerVolume.h 自定义一个Actor类,添加一个 Box 组件作为触发区域,然后通过重写虚函数——NotifyActorBeginOverlap, ...

  4. 【C++11新特性】 nullptr关键字

    原文链接:http://blog.csdn.net/xiejingfa/article/details/50478512 熟悉C++的童鞋都知道,为了避免“野指针”(即指针在首次使用之前没有进行初始化 ...

  5. Python 基础 json 与pickle

    json 支持:    str,int,tuple,list,dictpickle    支持python里所有的数据类型(包括函数)    只能在python中使用 json 与pickle 是一种 ...

  6. nginx技术分享 (转)

    原文地址:http://blog.csdn.net/nethibernate/article/details/6628267 Nginx的作用: HTTP Server 反向代理,用于将用户的请求转发 ...

  7. 学大伟业Day1解题报告

    学大伟业Day1解题报告 张炳琪 一.   时间分配 T1:30分钟  T2: 60分钟  T3:100分钟 二.答题情况及错因 T1:100         T2:55             T3 ...

  8. Kafka 基本原理

    Kafka 基本原理   来源:阿凡卢 , www.cnblogs.com/luxiaoxun/p/5492646.html 简介 Apache Kafka是分布式发布-订阅消息系统.它最初由Link ...

  9. Sass、Less编译器koala及koala不支持中文字体的解决方法

    一款很好用的Sass编译器,还可以编译Less.coffeescript等 去官网下载适合自己电脑的版本 http://koala-app.com/index-zh.html 打开后拖动或者打开项目目 ...

  10. laravel5.4中ajax删除数据

    1 JS代码 function deleteInfo(id) { if(id) { var r=confirm('确定要删除吗'); if(r==true) { $.ajax({ url: " ...