package com.fengche.utils;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2018/9/5
*/
public class URLUtils {
/**
* Get请求
*
* @param url
* @return
*/
public static String sendGet(String url) {
try {
URL u = new URL(url);
String res = inputStreamToString(u.openStream());
return res;
} catch (Exception e) {
System.out.println(url + ":get请求出错");
e.printStackTrace();
return null;
}
}
/**
* Post请求
*
* @param url
* @return
*/
public static String sendPost(String url) {
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
String res = inputStreamToString(con.getInputStream());
return res;
} catch (Exception e) {
System.out.println(url + ":post请求出错");
e.printStackTrace();
return null;
}
}
/**
* Post请求,json传参
*
* @param url
* @param params
* @return
*/
public static String sendPost(String url, Map<String, Object> params) {
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("POST");
//flag to true if you intend to use the URL connection for output.The default is false.
//要在请求体中传参,必须开启这个属性。默认为false
con.setDoOutput(true);
//设置参数形式为json
con.setRequestProperty("Content-Type", "application/json");
//传参
if (params.size() > 0) {
OutputStream out = con.getOutputStream();
out.write(new Gson().toJson(params).getBytes());
out.flush();
out.close();
}
//查看状态码
String res = inputStreamToString(con.getInputStream());
return res;
} catch (Exception e) {
System.out.println(url + ":post请求出错");
e.printStackTrace();
return null;
}
}
/**
* InputStream 转 String
*
* @param InputStream
* @return String
*/
public static String inputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int read = 0;
while ((read = inputStream.read(buf)) > 0) {
out.write(buf, 0, read);
}
//可设置gbk编码
String res = new String(out.toByteArray(), "utf-8");
out.close();
return res;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
String sb = "name";
Map<String,Object> params = new HashMap<>();
params.put("name","huang");
params.put("date","2018年9月5日");
String res = sendPost("http://localhost/info/post",params);
System.out.println(res);
}
}
自定义URL请求工具类: get请求以及带json参数的post请求
猜你喜欢
转载自blog.csdn.net/weixin_39454194/article/details/82427062
今日推荐
周排行