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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 Java 代编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值