示例代码:

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. Android - ContentProvider机制

    以下资料摘录整理自老罗的Android之旅博客,是对老罗的博客关于Android底层原理的一个抽象的知识概括总结(如有错误欢迎指出)(侵删):http://blog.csdn.net/luosheng ...

  2. linux 声音大小调整的命令

    alsamixer 输入上面的命令 回车即可看到图形界面,界面如下 ┌──────────────────────────── AlsaMixer v1.0.27.1 ──────────────── ...

  3. PHP的魔术方法(简介)

    public void _set(string $name,mixed $value) public mixed _get(string $name) public bool _isset(strin ...

  4. python 下的数据结构与算法---6:6大排序算法

    顶先最后推荐:哈哈,意思是放到顶部强调其重要性,但是应该我总结的六种算法看完了后再看的一篇醍醐灌顶的文章 一:冒泡排序(Bubble Sort) 原理:假设有n个数,第一轮时:从第一个元素开始,与相邻 ...

  5. SQL从入门到基础 - 04 SQLServer基础2(数据删除、数据检索、数据汇总、数据排序、通配符过滤、空值处理、多值匹配)

    一.数据删除 1. 删除表中全部数据:Delete from T_Person. 2. Delete 只是删除数据,表还在,和Drop Table(数据和表全部删除)不同. 3. Delete 也可以 ...

  6. spring 配置触发器 (类似于定时任务)

    为什么会看这个? 发现项目中有的service中的方法没有地方调用.经查,发现在web.xml中加载的spring的配置文件中配置了这个方法, 经查这种方式是触发器,会定时执行,只需要配置一下.可以设 ...

  7. Canvas前端游戏开发——FlappyBird详解

    一直想自己做点小东西,直到最近看了本<HTML5游戏开发>,才了解游戏开发中的一点点入门知识. 本篇就针对学习的几个样例,自己动手实践,做了个FlappyBird,源码共享在度盘;也可以参 ...

  8. keybd_event 转载

    转自 http://apps.hi.baidu.com/share/detail/14468670 Option Explicit Private Declare Sub keybd_event Li ...

  9. 一些不太常用的Linux命令

    ACCTCOM 查看所有用户执行过的进程 acctcom | tail - 查看指定用户执行过的进程/命令 acctcom -u <username> | tail - 使用一个正则表达式 ...

  10. ng-options

    tr td 地点 td select.form-control(required="true" ng-model="addkc.dd" ng-options=& ...