示例代码:

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. Qt Style Sheets帮助文档 Overview

    Qt Style Sheets are a powerful mechanism that allows you to customize the appearance of widgets, in ...

  2. java/php/c#版rsa签名以及java验签实现--转

    在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的功能之一.由于isv使用的开发语言不是单一的,因此sdk需要提供多种语言的版本.譬如java.php.c#.另外,在电子商务尤其是支付领 ...

  3. MVC的Model层中的一些便签

    由于自己重新接触MVC,所以把Model层里的一些标签给记录下来,方便自己的使用. 这些是自己目前试用过的一些,在以后的工作中我会接着补充进去新的内容

  4. solr官方文档翻译系列之schema.xml配置介绍

    常见的元素 <field name="weight" type="float" indexed="true" stored=" ...

  5. Example_07_05录音提示open failed: EACCES (Permission denied)

    在AndroidManifest.xml文件中加入下面这句话:<uses-permission android:name="android.permission.WRITE_EXTER ...

  6. gis基本概念之"投影变换"-浅谈

    目录 1,概述 2,常用的投影方法有 正解变换 反解变换 数值变换 3,定义投影 4,投影变换 1,栅格(投影变换) 2,要素(投影变换) 注意 1,概述 因为GIS描述的是位于地球表面的信息,所以根 ...

  7. swift 重载 泛式 inout的使用

    swift 重载 泛式 inout的使用 函数 func 关键字 -> 表示返回值信息等等 那我们接下来利用函数做几件事情 -a 比较两个数字的大小 -b 比较两个字符串 -c 既能比较字符串, ...

  8. HashMap工作原理

    hashmap存储的为key-value键值对,get的时间复杂度是O(1),具体实现原理如下: 1. hashmap是基于数组之上,通过一定算法,用空间转换时间 2. hashmap的数据结构为数组 ...

  9. phpcms v9 数据库分离部署

    v9数据模型功能,允许用户把不同的数据表,分离到不同的数据库服务器上.以实现负载的分离,更加的符合大访问网站的需求. <ignore_js_op> 数据分离方法 1.数据库连接配置配置文件 ...

  10. Serializable序列化

    对象的输入输出流 package file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutpu ...