Get请求
public static String getHttpJson(String urlStr) {
try {
URL url = new URL(urlStr);
//通url打开连接通道 Http
HttpURLConnection http = (HttpURLConnection) url.openConnection();
// (Https)
// HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
//设置请求方式
http.setRequestMethod("GET");
//设置请求超时时间 可有可无
http.setConnectTimeout(3000);
//设置数据读取超时时间 可有可无
http.setReadTimeout(60 * 1000);
//获取响应码
int responseCode = http.getResponseCode();
if (responseCode == 200) {
//获取读数据的流
InputStream is = http.getInputStream();
byte[] bys = new byte[1024];
int len = 0;
//创建用来临时存储数据的内存流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(bys)) != -1) {
baos.write(bys, 0, len);
}
//将内存流中的数据转成字符串
String json = baos.toString();
return json;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Post请求
public static String postJsonHttp(String urlString,String params){
// urlString 链接 params 参数
//封装URL对象
try {
URL url = new URL(urlString);
//打开了连接 Http
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// (Https)
// HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
//设置请求方式
urlConnection.setRequestMethod("POST");
//设置允许追加参数
urlConnection.setDoOutput(true);
//获取写数据的流
OutputStream os = urlConnection.getOutputStream();
//将数据写入
os.write(params.getBytes());
//强制将数据刷新到服务器
os.flush();
//设置连接时间 可有可无
urlConnection.setConnectTimeout(5000);
//设置读取超时时间 可有可无
urlConnection.setReadTimeout(60*1000);
//开始连接
urlConnection.connect();
//判断响应码
if(urlConnection.getResponseCode() == 200){
//获取读数据的流
InputStream is = urlConnection.getInputStream();
byte[] bys = new byte[1024];
int len = 0;
//创建用来临时存储数据的内存流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len = is.read(bys))!=-1){
baos.write(bys,0,len);
}
String json = baos.toString();
return json;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
微语
羡慕别人的天空简直没道理,因为你是一座宇宙。