美文网首页程序员
Java提交Http Get和Post请求的通用方法

Java提交Http Get和Post请求的通用方法

作者: 勿念及时雨 | 来源:发表于2019-12-14 23:00 被阅读0次

以往我们提交Http Get请求和Post请求时,一般会根据请求方式分别编写方法进行调用,以下方法则将两种请求的调用方式进行了整合,这样以后调用请求的时候就不需要考虑请求方式是Get还是Post,通通只要调用此方法就行了。代码如下:

public static ServiceResult sendRequest(String url, String obj, Map<String, String> headers, RequestMethod requestMethod, ContentType contentType) throws IOException {
    //返回对象,包含businessObject(返回数据)、success(是否成功返回)、
    //message(返回信息,一般是错误信息)、responseCode(返回码)等属性
    ServiceResult result = new ServiceResult();
        //Get提交时直接在url中拼接参数,obj是已经拼接好的参数字符串
    if (requestMethod.toString().equals("GET") && obj.length() > 0) {
        url = url + "?" + obj;
    }
    URL requestUrl = new URL(url);
    HttpURLConnection connection=null;
    StringBuffer sbBuffer = null;
    try {
        //打开连接,设置连接参数
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod(requestMethod.toString());
        //设置内容类型,默认为json
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "application/json");
        } else {
            connection.setRequestProperty("Content-Type",contentType);
        }
        connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
        connection.setRequestProperty("Accept", "*/*");
        //设置请求头,请求头信息存在map中,因此需要循环遍历出来进行设置
        if (headers != null) {
            for (Iterator iter = headers.keySet().iterator(); iter.hasNext();){
                String name = (String) iter.next();
                String value = String.valueOf(headers.get(name));
                connection.setRequestProperty(name, value);
            }
        }
        connection.setReadTimeout(2000000);
        connection.setConnectTimeout(2000000);
        connection.connect();
        //如果是post请求,则需要将参数写入到输出流中
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(obj.toString().getBytes());
        outputStream.flush();
        outputStream.close();
        //获取返回结果码
        int code = connection.getResponseCode();
        if (code == 200) {//返回成功的结果码
            //从输入流中读取返回信息
            InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(inputStreamReader);
            sbBuffer = new StringBuffer("");
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sbBuffer.append(lines);
            }
            reader.close();
            inputStreamReader.close();
            //将返回信息设置到返回对象中
            result.setResponseCode(200);
            result.setIsSuccess(true);
            result.setBusinessObject(sbBuffer.toString());
        } else {//返回失败
            //将返回失败信息设置到返回对象中
            result.setBusinessObject(connection.getResponseMessage());
            result.setMessage(connection.getResponseMessage());
            result.setResponseCode(connection.getResponseCode());
            result.setIsSuccess(false);
        }
        //断开连接
        connection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        //将异常信息设置到返回对象中
        result.setIsSuccess(false);
        result.setMessage(e.getMessage());
        result.setResponseCode(0);
    }
    return result;
}

相关文章

  • Java提交Http Get和Post请求的通用方法

    以往我们提交Http Get请求和Post请求时,一般会根据请求方式分别编写方法进行调用,以下方法则将两种请求的调...

  • 调用http请求

    调用http请求 http请求方法(POST 和 GET)

  • retrofit注解

    @GET 表示get请求 @POST 表示post请求 @HTTP 比较通用 @Straming 表示响应体的数据...

  • http中post请求和get请求的区别

    GET和POST是HTTP请求的两种基本方法: GET:主要用来从指定的资源请求数据 POST:主要用来提交要被处...

  • HTTP、HTTPS

    HTTP HTTP请求格式image.png 请求方法: 9种GET:向指定的资源发出请求POST:向指定资源提交...

  • 可能碰到的iOS笔试面试题(16)--网络

    网络 http请求方式? 通常,HTTP的请求方式有3种,分别是:POST、GET、HEAD。POST和GET方法...

  • get 和post 请求的区别

    get和post请求区别: 1.get请求提交的内容都在网址后面(URL后面),而post请求的内容都在http响...

  • 面试总结

    1.get和post比较 1>提交方式:GET提交,请求的数据会附在URL之后;POST提交则把数据放置在HTTP...

  • post 和 get 方式提交数据有什么区别?

    如果服务端和客户端在符合语义的条件下处理了HTTP的post方法和get方法提交的请求的情况下,post和get方...

  • java网络请求代码

    记录一个Java网络请求的工具类,post是以json的形式提交请求的 里面包含了get 和post的方法可以直接...

网友评论

    本文标题:Java提交Http Get和Post请求的通用方法

    本文链接:https://www.haomeiwen.com/subject/exbhnctx.html