原生方式:@转载文章

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连接的更多相关文章

  1. 编写爬虫(spider)的预备知识:用java发送HTTP请求

    使用原生API来发送http请求,而不是使用apache的库,原因在于这个第三方库变化实在太快了,每个版本都有不小的变化.对于程序员来说,使用它反而会有很多麻烦,比如自己曾经写过的代码将无法复用. 原 ...

  2. 通过java发送http请求

    通常的http请求都是由用户点击某个连接或者按钮来发起的,但是在一些后台的Java程序中需要发送一些get或这post请求,因为不涉及前台页面,该怎么办呢? 下面为大家提供一个Java发送http请求 ...

  3. java发送带附件的邮件

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

  4. java ssl https 连接详解 生成证书 tomcat keystone

    java ssl https 连接详解 生成证书 我们先来了解一下什么理HTTPS 1. HTTPS概念 1)简介 HTTPS(全称:Hypertext Transfer Protocol over ...

  5. JAVA实现长连接(含心跳检测)Demo

    实现原理: 长连接的维持,是要客户端程序,定时向服务端程序,发送一个维持连接包的.       如果,长时间未发送维持连接包,服务端程序将断开连接. 客户端:       Client通过持有Sock ...

  6. JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理

    java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...

  7. java发送email一般步骤

    java发送email一般步骤 一.引入javamail的jar包: 二.创建一个测试类,实现将要发送的邮件内容写入到计算机本地,查看是否能够将内容写入: public static void mai ...

  8. JAVA 网络长短连接

       作为java的刚開始学习的人,看了网上的资料后,关于java的长短连接,感觉理解的不是非常深刻.结合自己的学习和网上的资料整理例如以下.不对之处请大家批评指正.                  ...

  9. Java 发送http GET/POST请求

    最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑 HttpURLConnection HttpURLConnection是一种多用途.轻量极的HTTP客户端,使 ...

随机推荐

  1. Linux主题:获取帮助

    Linux有多种方式获取帮助,这些帮助通过不同的命令,获得不同详细程度和文字量的帮助. help help方式有两种用法,一种是help command,另一种是command --help.前一种是 ...

  2. 使用mysqlbinlog恢复指定表

    从整库备份的sql文件中导出某个表的sql语句时,vim查找到表的第一条INSERT语句后,按上下换行键计数INSERT语句的条数,然后按n yy复制,退出vim后,再新建一个文件,按p粘贴刚才的n条 ...

  3. 减少mysql主从数据同步延迟

    网上给出的解决办法: 基于局域网的master/slave机制在通常情况下已经可以满足'实时'备份的要求了.如果延迟比较大,就先确认以下几个因素:1. 网络延迟2. master负载3. slave负 ...

  4. linux 3.10的list_del

    最近看到一个page的数据比较奇怪: crash> page ffffea002c239c58 struct page { flags = , _count = { counter = 34-- ...

  5. MySql出现大量LAST_ACK的解决办法

    前几日生产环境遇到一问题,网站的同步登录部分提示Can’t connect to MySQL server on ‘localhost’ (10060),第一反应就是可能过连接数据库的相关参数了,经检 ...

  6. 通用坐标投影转换器Uneversal Coord Transformer

    关键词:投影,重投影,坐标转换,坐标系,空间参考,北京54,西安80,中国2000,WGS84,UTM,墨卡托,网络墨卡托 软件名称:通用坐标投影转换器Uneversal Coord Transfor ...

  7. C++ CSTRINGLIST用法

    CStringList类成员   构造 CStringList 构造一个空的CString对象列表 首/尾访问 GetHead 返回此列表(不能是空的)中头部的元素 GetTail 返回此列表(不能是 ...

  8. 在使用 #import <objc/message.h>时 xcode 报 :Too many arguments to function call, expected 0 , have * 解决方法

    选中项目 - Project - Build Settings - 

  9. ABAP 常用函数

    函数名 描述 SD_VBAP_READ_WITH_VBELN 根据销售订单读取表vbap中的信息EDIT_LINES 把READ_TEXT返回的LINES中的行按照TDFORMAT=“*”重新组织VI ...

  10. gradle 很好用的么

    Gradle 其实是很好用的 2017, Apr 14 by Tesla Ice Zhang Gradle 是一款使用 Kotlin (划掉) Groovy 编写的 JVM 构建工具,其易用性和 Ma ...