示例代码:

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. vim 开发配置(转载)

    原文:http://www.cnblogs.com/ma6174/archive/2011/12/10/2283393.html 花了很长时间整理的,感觉用起来很方便,共享一下. 我的vim配置主要有 ...

  2. SWFObject文件上传使用记录

    SWFObject文件上传使用方法记录,该插件使用起来相当强大也很灵活,与uploadify各有千秋. 值得一说的是,如果要设置button_image_url这个参数,该参数是按钮的背景图,但是一定 ...

  3. Topcoder SRM 639 (Div.2)

    A.ElectronicPetEasy [题意]一个数st1开始,每次加p1,一共加t1次,另外一个数st2开始,每次加p2,一共加t2次,输入的数均小于1000,问这两个数有没有可能相等,有可能输出 ...

  4. 【网络流#2】hdu 1533 - 最小费用最大流模板题

    最小费用最大流,即MCMF(Minimum Cost Maximum Flow)问题 嗯~第一次写费用流题... 这道就是费用流的模板题,找不到更裸的题了 建图:每个m(Man)作为源点,每个H(Ho ...

  5. nyoj 76

    #include <iostream> using namespace std; int main() { int i,t,n; int a[101]; cin>>t; whi ...

  6. Examples_08_08

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARYAAAGsCAIAAACXfh8LAAAgAElEQVR4nO2db3AT193v903e8yIzbV

  7. Jenkins学习之——(4)Email Extension Plugin插件的配置与使用

    1.先安装插件 2.配置 点击高级后 内容配置: 3.项目配置 点击Advanced Settings后 到此所有的配置都设置完成. 附录: 以下内容来自其他网友的博客,内容也没有自己去试,朋友们可以 ...

  8. 微信企业号开发遇到的bug

    a. 微信嵌入视频: a.1 视频元素播放时层级默认被顶置 a.1 视频播放后窗口无法通过css改变层级 a.2 视频播放后窗口无法通过css隐藏 解决方案:做个虚假的播放窗口,点击播放窗口(虚假的) ...

  9. querySelector选择器

    querySelector选择器可以通过document和element来调用他们 用来代替getElementById var body=document.querySelector("b ...

  10. css与div小结

    前些时间学习css与div的课程 什么是css呢 Css 级联样式表或层叠样式表(Cascading Style Sheet) 是能够真正做到 网页表现与内容分离的一种样式设计语言.相对于传统HTML ...