在java中http的get和post请求
程序员文章站
2022-05-09 10:28:11
...
一个比较简单的工具类,不多解释了,直接上代码
package com.sharebo.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* http转发工具类
* @author 郭鹏飞
*
*/
public class HttpUtil {
/**
* http get请求
* <blockquote><pre>
* 返回数据拼装为String类型<p>
* 如果需要返回其他类型的数据,请另写方法改动
* </pre></blockquote>
* @param httpUrl
* @return
*/
public static String request_get(String httpUrl) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(20000);
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
//e.printStackTrace();
}
return result;
}
/**
* http post请求
* @param httpUrl
* @param httpArg
* @return
*/
public static String request_post(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(20000);
connection.getOutputStream().write(httpArg.getBytes("UTF-8"));
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
推荐阅读
-
Linux下模拟http的get/post请求(curl or wget)详解
-
python通过get,post方式发送http请求和接收http响应的方法
-
ajax请求post和get的区别以及get post的选择
-
postman的安装与使用方法(模拟Get和Post请求)
-
使用PHP Socket 编程模拟Http post和get请求
-
.NET Core Razor Pages中ajax get和post的使用
-
php中$_REQUEST、$_POST、$_GET的区别和联系小结
-
如何解决Ajax访问不断变化的session的值不一致以及HTTP协议中的GET、POST的区别
-
Angularjs中$http以post请求通过消息体传递参数的实现方法
-
[日常] 使用TCPDUMP和Ethereal抓包分析HTTP请求中的异常情况