package com.http.https;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Http {
/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
public static void main(String[] args) {
String httpUrl = "http://apis.baidu.com/apistore/weatherservice/citylist";
String httpArg = "cityname=%E6%9C%9D%E9%98%B3";
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//setRequestProperty()往http请求头增加参数(根据接口需要,此处需要增加apikey)
connection.setRequestProperty("apikey", "034da992caf945858883f7ca01017c04");
//打开连接(因为是使用的http get方式,不再用流形式传递参数过去,所以此处就已经将请求发送过去了)
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();
String result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
http get请求
最新推荐文章于 2024-05-20 19:36:12 发布