java发送http连接
原生方式:@转载文章
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;
import java.util.Map; import org.apache.commons.lang.StringUtils; public class HttpGetUtil {
/**
* Post 请求超时时间和读取数据的超时时间均为2000ms。
*
* @param urlPath post请求地址
* @param parameterData post请求参数
* @return String json字符串,成功:code=1001,否者为其他值
* @throws Exception 链接超市异常、参数url错误格式异常
*/
public static String doPost(String urlPath, String parameterData, String who, String ip) throws Exception { if (null == urlPath || null == parameterData) { // 避免null引起的空指针异常
return "";
}
URL localURL = new URL(urlPath);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.setDoOutput(true);
if (!StringUtils.isEmpty(who)) {
httpURLConnection.setRequestProperty("who", who);
}
if (!StringUtils.isEmpty(ip)) {
httpURLConnection.setRequestProperty("clientIP", ip);
}
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()));
httpURLConnection.setConnectTimeout(18000);
httpURLConnection.setReadTimeout(18000); OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuilder resultBuffer = new StringBuilder();
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();
} public static String doPost(String url, Map<String, Object> params) throws Exception {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
} // no matter for the last '&' character return doPost(url, sb.toString(), "", "");
} /**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String who, String ip) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
if (!"".equals(param)) {
urlNameString = urlNameString + "?" + param;
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
if (!StringUtils.isEmpty(who)) {
connection.setRequestProperty("who", who);
}
if (!StringUtils.isEmpty(ip)) {
connection.setRequestProperty("clientIP", ip);
}
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect(); // 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} public static String sendGet(String url, Map<String, Object> params) throws Exception {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
} // no matter for the last '&' character return sendGet(url, sb.toString(), "", "");
} }
更多方式:@参考文章
java发送http连接的更多相关文章
- 编写爬虫(spider)的预备知识:用java发送HTTP请求
使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...
- 通过java发送http请求
通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...
- java发送带附件的邮件
/** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...
- java ssl https 连接详解 生成证书 tomcat keystone
java ssl https 连接详解 生成证书 我们先来了解一下什么理HTTPS 1. HTTPS概念 1)简介 HTTPS(全称:Hypertext Transfer Protocol over ...
- JAVA实现长连接(含心跳检测)Demo
实现原理: 长连接的维持,是要客户端程序,定时向服务端程序,发送一个维持连接包的. 如果,长时间未发送维持连接包,服务端程序将断开连接. 客户端: Client通过持有Sock ...
- JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理
java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...
- java发送email一般步骤
java发送email一般步骤 一.引入javamail的jar包: 二.创建一个测试类,实现将要发送的邮件内容写入到计算机本地,查看是否能够将内容写入: public static void mai ...
- JAVA 网络长短连接
作为java的刚開始学习的人,看了网上的资料后,关于java的长短连接,感觉理解的不是非常深刻.结合自己的学习和网上的资料整理例如以下.不对之处请大家批评指正. ...
- Java 发送http GET/POST请求
最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑 HttpURLConnection HttpURLConnection是一种多用途.轻量极的HTTP客户端,使 ...
随机推荐
- Delphi处理TWebBrowser的Close事件
当TWebBrowser控件访问的 Web 页上的脚本调用window.close方法时,TWebBrowser控件可能会在窗体中消失.我们的程序应该对此作出反应,否则再次访问TWebBrowser控 ...
- CSS 的 ID 和 Class 有什么区别,如何正确使用它们。
css只用class来写并有专门的class通用和私有模块命名, id具有唯一性且优先级太高只作为js操作dom的挂钩全部不添加样式, 如果使用jq或zepto的话,操作的class类名一般也不加样式 ...
- EMQ笔记
飞行窗口(Inflight Window)保存当前正在发送未确认的Qos1/2消息.窗口值越大,吞吐越高:窗口值越小,消息顺序越严格. 当客户端离线或者飞行窗口(Inflight Window)满时, ...
- 2339 3.1.1 Agri-Net 最短网络
Description 农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场.当然,他需要你的帮助. 约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享 ...
- 函数mmap()的使用
函数mmap是linux的一个系统函数.如下: 函数原型:void *mmap(void *addr, size_t length, int prot, int flags,int fd, off_t ...
- servlet(2)response常用方法
详细的response 学习笔记是: 输出到前台的的方法 1:使用OutputStream流向客户端浏览器输出中文数据 2:使用PrintWriter流向客户端浏览器输出中文数据 3:使用Output ...
- repo 原理
Android源代码工程用repo来进行管理,本质是多个git仓的整合. 感谢https://blog.csdn.net/stoic163/article/details/78790349 1.Gen ...
- hibernate 工作原理及为什么要用
- Docker 批量启动
批量配置IP for i in `docker ps -a|awk 'NR>1 {print $NF}'`;do IP=`echo $i|awk -F_ '{print "192.16 ...
- How to fix the bug “Expected "required", "optional", or "repeated".”?
参考:https://github.com/tensorflow/models/issues/1834 You need to download protoc version 3.3 (already ...