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. 1117 Eddington Number (25 分)

    1117 Eddington Number (25 分) British astronomer Eddington liked to ride a bike. It is said that in o ...

  2. Fragment之介绍(转)

    http://www.cnblogs.com/plokmju/p/3239265.html 前言 开门见山开篇名义,本篇博客将讲解一下Android中Fragment的内容,必要的地方会提供相应的演示 ...

  3. mysql存储过程中遍历数组字符串的两种方式

    第一种:多次使用substring_index()的方法 DELIMITER $$ DROP PROCEDURE IF EXISTS `array`$$ CREATE  PROCEDURE `arra ...

  4. 对于分类问题的神经网络最后一层的函数:sigmoid、softmax与损失函数

    对于分类问题的神经网络最后一层的函数做如下知识点总结: sigmoid和softmax一般用作神经网络的最后一层做分类函数(备注:sigmoid也用作中间层做激活函数): 对于类别数量大于2的分类问题 ...

  5. 给iOS开发新手送点福利,简述UIImagePickerController的属性和用法

    1.+(BOOL)isSourceTypeAvailable:(UIImagePickerControllerSourceType)sourceType;         // 检查指定源是否在设备上 ...

  6. python的eval、exec函数使用总结

    eval函数 一.函数的作用 将字符串str当成有效的表达式来求值并返回计算结果.它要执行的python代码只能是单个运算表达式(不支持任意形式的赋值操作),而不能是复杂的代码逻辑. 二.函数的定义 ...

  7. SQL Server2016 配置管理器

    SQL Server2016 以后版本配置管理器的配置管理器不再同数据库工具集成,是单独的应用. Windows 10: 要打开 SQL Server 配置管理器,请在“起始页”中键入 SQLServ ...

  8. [Flutter] 一些面试可能会问基础知识

    1. Flutter 是什么? Flutter是谷歌的移动UI框架,可以快速在iOS和Android上构建高质量的原生用户界面. Flutter可以与现有的代码一起工作.在全世界,Flutter正在被 ...

  9. jap _spring _maven

    pom.xm <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3 ...

  10. ActiveMQ无法启动

    解决办法:activemq无法启动,端口被占用 用netstat -an无法查出61616被哪个进程占用(实践证明,netstat -ano|findstr '61616'什么也没有找到) 经过排查和 ...