示例代码:

package com.shareboxes.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.junit.Ignore;
import org.junit.Test; /**
* @ClassName: HttpRequest
* @Description: get,post请求
* @author Administrator
* @date 2015年10月19日
*
*/ public class HttpRequest { /**
* @Title: sendGet
* @Description: get请求
* @param url
* @param param
*/
public static String sendGet(String url, Map<String, String> param) {
BufferedReader bReader = null;
StringBuffer sBuffer = new StringBuffer();
String realUrl = url; try { if (param.size() > 0) {
realUrl += "?";
for (Entry<String, String> entry : param.entrySet()) {
realUrl += entry.getKey() + "=" + entry.getValue() + "&";
}
realUrl = realUrl.substring(0, realUrl.length() - 1);
} URL urlString = new URL(realUrl);
URLConnection urlConnection = urlString.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setRequestMethod("GET");// 设置请求方法
httpURLConnection.setConnectTimeout(30000);// 连接主机超时时间
httpURLConnection.setReadTimeout(30000);// 读取数据超时时间
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置请求数据的格式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");// 设置接收数据的编码 // 判断连接是否异常
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} System.out.println(httpURLConnection.getResponseCode());
for(Entry<String, List<String>>entry:httpURLConnection.getHeaderFields().entrySet()){
System.out.println(entry.getKey()+"--------->"+entry.getValue());
} bReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = bReader.readLine()) != null) {
sBuffer.append(line);
}
} catch (Exception e) {
System.out.println("get 请求发生错误!!!");
e.printStackTrace();
} finally {
if (bReader != null) {
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sBuffer.toString();
} /**
* @Title: sendPost
* @Description: post请求
* @param url
* @param param
*/
public static String sendPost(String url, Map<String, String> param) {
BufferedReader bReader = null;
OutputStreamWriter out = null;
StringBuffer sBuffer = new StringBuffer();
String parameterData =""; try {
if (param.size() > 0) {
for (Entry<String, String> entry : param.entrySet()) {
parameterData += entry.getKey() + "=" + entry.getValue() + "&";
}
parameterData = parameterData.substring(0, parameterData.length() - 1);
} URL realUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection(); httpURLConnection.setConnectTimeout(30000);
httpURLConnection.setReadTimeout(30000);
httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setInstanceFollowRedirects(true); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置请求参数的格式
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");// 接收数据的编码 if((parameterData.trim().length()>0) && (!parameterData.equals(""))){
out = new OutputStreamWriter(httpURLConnection.getOutputStream(), "utf-8");
out.write(parameterData);
out.flush();
} // 判断连接是否异常
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
} System.out.println(httpURLConnection.getResponseCode());
for(Entry<String, List<String>>entry:httpURLConnection.getHeaderFields().entrySet()){
System.out.println(entry.getKey()+"--------->"+entry.getValue());
} // bReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
// String line = null;
// while ((line = bReader.readLine()) != null) {
// sBuffer.append(line);
// } InputStream in=httpURLConnection.getInputStream();
byte []data=new byte[httpURLConnection.getContentLength()];
int offset=0;
while(offset<in.available()){
offset+=in.read(data, offset, in.available()-offset);
System.out.println(offset);
}
sBuffer.append(new String(data,"utf-8"));
} catch (Exception e) {
System.out.println("post 请求失败!!!");
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (bReader != null) {
bReader.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return sBuffer.toString();
} @Test
@Ignore
public void testGet() {
Map<String, String> param = new HashMap<String, String>();
param.put("tid", "1");
System.out.println(sendGet("http://localhost:8080/shareboxes/record/getrecord/tid.do", param));
} @Test
public void testPost() {
Map<String, String> param = new HashMap<String, String>();
param.put("tid", "1");
System.out.println(sendPost("http://localhost:8080/shareboxes/record/getrecord/tid.do", param));
} }

java中post和get请求的更多相关文章

  1. java中模拟http(https)请求的工具类

    在java中,特别是java web中,我们经常需要碰到的一个场景是我们需要从服务端去发送http请求,获取到数据,而不是直接从浏览器输入请求网址获得相应.比如我们想访问微信接口,获取其返回信息. 在 ...

  2. 【SpringBoot】 Java中如何封装Http请求,以及JSON多层嵌套解析

    前言 本文中的内容其实严格来说不算springboot里面的特性,属于JAVA基础,只是我在项目中遇到了,特归纳总结一下. HTTP请求封装 目前JAVA对于HTTP封装主要有三种方式: 1. JAV ...

  3. java中获取所有的请求参数

    //获取所有的请求参数 Enumeration<String> paraNames=request.getParameterNames(); for(Enumeration<Stri ...

  4. spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

    在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实 ...

  5. java中如何模拟真正的同时并发请求?

    有时需要测试一下某个功能的并发性能,又不要想借助于其他工具,索性就自己的开发语言,来一个并发请求就最方便了. java中模拟并发请求,自然是很方便的,只要多开几个线程,发起请求就好了.但是,这种请求, ...

  6. JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例

    一.简述需求 平时我们需要在JAVA中进行GET.POST.PUT.DELETE等请求时,使用第三方jar包会比较简单.常用的工具包有: 1.https://github.com/kevinsawic ...

  7. Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件)

    Java中使用HttpPost上传文件以及HttpGet进行API请求(包含HttpPost上传文件) 一.HttpPost上传文件 public static String getSuffix(fi ...

  8. java中的锁

    java中有哪些锁 这个问题在我看了一遍<java并发编程>后尽然无法回答,说明自己对于锁的概念了解的不够.于是再次翻看了一下书里的内容,突然有点打开脑门的感觉.看来确实是要学习的最好方式 ...

  9. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

随机推荐

  1. jQuery UI Widget(1.8.1)工作原理--转载

    先看下代码的相关注释: /*! * jQuery UI Widget 1.8.1 * * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/abo ...

  2. java图片处理工具类

    直接上代码: package com.zxd.tool; /** * Created by zhang on 14-3-1. * 图片的常用操作类 */ import java.awt.AlphaCo ...

  3. apache SetEnv 设置

    php的服务器预定义变量 $_SERVER 可以通过apache的mod_env模块来添加我们所需要的内容 来段官网介绍 Description: Modifies the environment w ...

  4. vim命令---存阅

    命令历史 以:和/开头的命令都有历史纪录,可以首先键入:或/然后按上下箭头来选择某个历史命令. 启动vim 在命令行窗口中输入以下命令即可 vim 直接启动vim vim filename 打开vim ...

  5. 小学生之使用Mybatis反向生成dao,entity,xml

    本小学生刚进公司的时候,就一顿装逼,不管别人问我啥我都会说:"会"!毕竟在公司吗,什么都要装,不要别人看出你的底细.不过有一天,听说用Mybatis可以反向生成dao(第一次听说) ...

  6. SQL 2008 清除数据库日志

    USE [master]GOALTER DATABASE DNName SET RECOVERY SIMPLE WITH NO_WAITGOALTER DATABASE DNName SET RECO ...

  7. 刚接触js感觉好吃力啊

    我是一个新手,最近刚刚开始学习js这门语言,感觉好难,有一种无从下手的感觉,不知道应该从哪里学习,虽然也看了很多的书,但是对于一个没有计算机基础的人来说,真的是一种煎熬,每一个名词都要去查.万事开头难 ...

  8. 关于JS、JQuery、CSS的小知识点

    1.将字符串转换成json列表格式如下: var getaddress = appcan.libuser.getAddress(); var address=JSON.parse(getaddress ...

  9. PHP Socket编程起步

    让我们以一个简单的例子开始---一个接收输入字符串,处理并返回这个字符串到客户端的TCP服务.下面是相应的代码: PHP 代码: ) or die("Could not read input ...

  10. MySQL中的binlog相关命令和恢复技巧

    操作命令: 复制代码 代码如下: show binlog events in 'mysql-bin.000016' limit 10; reset master 删除所有的二进制日志 flush lo ...