通過HttpURLConnection發送GET和POST請求
public class HttpURLConnectionDemo {
/**
* get
* @param httpUrl 請求
* @param encode 編碼
* @return
*/
public static String deGet(String httpUrl,String encode){
if(encode == "" || encode == null){
//設置默認編碼
encode = "utf-8";
}
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try{
//創建遠程url連接對象
URL url = new URL(httpUrl);
//通過遠程url連接對象打開一個連接,強轉成HTTPURLConnection類
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//設置連接超時時間和讀取超時時間
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//發送請求
conn.connect();
//通過conn取得輸入流,並使用Reader讀取
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, encode));
String line;
while ((line = br.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
conn.disconnect();
}
return result.toString();
}
/**
* post
* @param httpUrl 請求
* @param encode 編碼
* @return
*/
public static String doPost(String httpUrl,String encode){
if(encode == "" || encode == null){
//設置默認編碼
encode = "utf-8";
}
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try{
URL url = new URL(httpUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//發送POST請求必須設置爲true
conn.setDoOutput(true);
conn.setDoInput(true);
//設置連接超時時間和讀取超時時間
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//獲取輸出流
out = new OutputStreamWriter(conn.getOutputStream());
String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
out.write(jsonStr);
out.flush();
out.close();
//取得輸入流,並使用Reader讀取
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode));
String line;
while ((line = in.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}
return result.toString();
}
public static void main(String[] args) {
String url = "http://57.145.140.145:7776/tyc/getTycInfo?params=%7B%22id%22:%22%22,%22name%22:%22%E5%9B%9B%E5%B7%9D%E5%B7%9D%E5%A4%A7%E6%99%BA%E8%83%9C%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%7D&url=http:%2F%2Fopen.api.tianyancha.com%2Fservices%2Fv4%2Fopen%2Fpast%2Fic";
System.out.println(deGet(url,""));
}
}
關於轉義碼問題
發現如果是瀏覽器拷貝過來字符通過了
String url = “http://57.145.140.145:7776/tyc/getTycInfo?params=%7B%22id%22:%22%22,%22name%22:%22%E5%9B%9B%E5%B7%9D%E5%B7%9D%E5%A4%A7%E6%99%BA%E8%83%9C%E7%B3%BB%E7%BB%9F%E9%9B%86%E6%88%90%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8%22%7D&url=http:%2F%2Fopen.api.tianyancha.com%2Fservices%2Fv4%2Fopen%2Fpast%2Fic”;
而沒有轉義符的會出現400錯誤
原因是編碼問題
文件格式可能不是utf-8,我們可以把參數在統一轉碼一下。
String url2 = null;
try {
url2 = "http://58.130.66.120/gzeimm_web/capDec2/getEnpFillInfo.rpcc?parameter=" +
URLEncoder.encode("{\"date\":\"2020-05-11\"}", "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url3= "http://58.130.66.120/gzeimm_web/capDec2/getEnpFillInfo.rpcc?parameter={%22date%22:%222020-05-11%22}%22";
上面兩個請求是正常滴。
建議在方法中對參數轉碼
關於參數建議
參數我們可以用map添加
Map<String, String> param = new HashMap<String, String>();
param.put("report_period", "2020-5");
param.put("pageSize", "10");
param.put("pageIndex", "1");
方法中把map放入url中,調用方法時清晰方便。