HttpURLConnection的工具类

一.第一步先创建一个类
1.类里面有一个JSON解析的方法

  //执行get请求,返回String结果
  public static String getRequest(String urlStr) {
    String result = "";
    try {
      URL url = new URL(urlStr);
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setConnectTimeout(5000);
      urlConnection.setReadTimeout(5000);
      int responseCode = urlConnection.getResponseCode();
      if(responseCode == 200) {
        result = stream2String(urlConnection.getInputStream());
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }

2.将字节流转换成字符

 private static String stream2String(InputStream is) throws IOException {


InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder stringBuilder = new StringBuilder();

for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) {
  stringBuilder.append(tmp);
}

	return stringBuilder.toString();
 }

3.执行get请求,返回Bean

 public static <E> E getRequest(String urlStr, Class clazz) {
	String result = getRequest(urlStr);
    E e = (E) new Gson().fromJson(result, clazz);
	return e;
}

猜你喜欢

转载自blog.csdn.net/weixin_43587850/article/details/83684875