通过HttpURLConnection发送GET和POST请求(解决转义码问题)

通过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中,调用方法时清晰方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章