1、一个自定义url请求工具类
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestUtils {
//post请求
public static String postRequest(String postUrl){
try{
URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置POST请求
connection.setRequestMethod("POST");
//缺少此项可能会出现请求失败的情况
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
// 设置可向服务器输出
connection.setConnectTimeout(5000);//超时设定
// 打开连接
connection.connect();
//至此,就可以通过后台进行debug验证是否成功请求了
// 提交数据后,获取来自服务器的json数据
if (connection.getResponseCode() == 200) {
//使用字符流形式进行回复
InputStream is = connection.getInputStream();
//读取信息BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
buffer.append(readLine);
}
is.close();
reader.close();
connection.disconnect();
return buffer.toString();
}
return "post请求失败";
}
catch (Exception e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
}
//get请求
public static String getRequest(String getUrl){
try{
//创建URL对象
URL url = new URL(getUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//开启连接
connection.setRequestMethod("GET");
connection.connect();//连接服务器
//Log.d("zhang", "getRequest: "+"到这里了");
//然后是对于请求返回的接收
if (connection.getResponseCode() == 200){
//使用字符流形式进行回复
InputStream is = connection.getInputStream();
//读取信息BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String readLine = "";
while ((readLine = reader.readLine()) != null) {
buffer.append(readLine);
}
is.close();
reader.close();
connection.disconnect();
return buffer.toString();
}
return "get请求失败";
}catch (Exception e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
}
}
这是一个用Java编写的自定义HTTP请求工具类,包括POST和GET两种请求方式。类中定义了连接超时时间和数据传输格式,能处理HTTP响应状态码为200的情况,并将服务器返回的JSON数据转换为字符串。若请求失败,会返回错误信息。
251

被折叠的 条评论
为什么被折叠?



