原生方式:@转载文章

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. LeetCode 题解 Search a 2D Matrix II。巧妙!

    [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30 ...

  2. 利用官方的vue-cli脚手架来搭建Vue集成开发环境

    在利用vue-cli脚手架搭建vue集成环境之前,我们需要先安装nodejs的环境.如果在cmd中输入node --version和npm --version出现如下的版本信息,就说明安装已经成功了. ...

  3. webkit内核自定义隐藏滚动条

    1,在主页面可以拿到iframe,也可以为iframe注册onload等事件.document.getElementById('iframeId').onload 2,在主页面操作其中的iframe的 ...

  4. DELPHI 对象的本质 VMT

    http://www.cnblogs.com/little-mat/articles/2206627.html TObject是所有对象的基本类,DELPHI中的任何对象都是一个指针,这个指针指明该对 ...

  5. AngularJS理论知识

    两个核心概念 三个架构 MVC 一切应用程序都是数据的增删改查 那么总要有东西装数据吧 Model就是干这个事(数据表现和操作) View(展现数据) Controller(逻辑) 那么M- V- C ...

  6. Structs复习 开始 第一个helloworld项目

    大体已经学完ssh了  感觉一起做一个项目有点难 计划先用一下独立的Structs 然后再把数据库操作换成hibernate  然后在用Spring 整合 计划用10天左右吧 但今天开始用Struct ...

  7. HTML+CSS基础课程二

    1.border为系统加边框<style type="text/css"> table tr td,th{border:1px solid #000;} </st ...

  8. C++ vc中怎么使用SendMessage自定义消息函数

    vc中怎么使用SendMessage自定义消息函数: SendMessage的基本结构如下:SendMessage(    HWND hWnd,  //消息传递的目标窗口或线程的句柄.    UINT ...

  9. ROS:ROS操作类MK.cs

    class MK { Stream connection; TcpClient con; public MK(string ip,int port) { con = new TcpClient(); ...

  10. hdu1042-N!-(java大数)

    题目:求n!(0<=n<=10000) import java.math.BigInteger;//操作大整数 import java.math.BigDecimal;//操作大小数 im ...