HttpURLConnection请求RestFull风格后台

在面对Restful风格的后台接口时,使用Volley网络框架可能会遇到问题,特别是在处理自定义状态码时。本文通过实例代码展示了如何使用HttpURLConnection直接进行封装,以适配Restful风格的请求,特别强调了在不同状态码下正确获取响应流的方法。虽然这种方式在性能上可能稍逊一筹,但能有效解决Volley无法处理自定义状态码的问题。
摘要由CSDN通过智能技术生成


       最近Restfull风格比较火,公司很坑,后台外包出去。外包公司扔过来的接口正式restfull风格,一开始看到接口很懵逼。

看懂会用,还是没多大毛病,毛病就出在网络框架不再适合用了。


    公司的项目用的是volley作网络框架,正常的访问没啥问题,restfull,就需要注意了。

   后台请求时要添加请求头,这个时候只能自己再做相应封装一下:


   直接贴代码:

/**
 * @author: ZengWQ(zwq_em@163.com)
 * Date: 2017-12-13
 * Time: 10:43
 * Verssion: 1.0
 * Describe: 
 */
public class CommonRequst extends StringRequest {
    public CommonRequst(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
    }

    public CommonRequst(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(url, listener, errorListener);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {

        Map<String ,String>headers=super.getHeaders();
        if (headers==null|headers.equals(Collections.<String, String>emptyMap())){
            headers=new HashMap<String, String>();
        }
           headers.put("XXX","xxx");//添加请求头
        return headers;
    }
}

然而:


  这么处理只能解决正常http协议中的状态码:


  后台自定义的状态码时,volley框架就不行了:贴下异常

    java.net.ProtocolException: Unexpected status line: HTTP/1.0 1012 UNKNOWN  

  

   正常情况 响应头的信息是:  HTTP/1.0 200 ok


  而这个1012  是restfull风格中自己定义的响应码,这个时候标准的volley框架就解析不到1012 是什么意思,直接抛异常;

  因为需求着急,自己动手丰衣足食,自己撸了一段代码去适配这个restfull风格。


  上代码:



    

/**
 * @author: ZengWQ(zwq_em@163.com)
 * Date: 2017-12-18
 * Time: 15:30
 * Verssion: 1.0
 * Describe: 该http是封装给restfull风格用
下面是使用Java中的HttpURLConnection类构建RESTful API POST请求的简单示例: ``` URL url = new URL("https://jsonplaceholder.typicode.com/posts"); // Create connection object HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Set request method to POST httpURLConnection.setRequestMethod("POST"); // Set headers httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8"); httpURLConnection.setRequestProperty("Accept", "application/json"); // Enable output and set content length httpURLConnection.setDoOutput(true); String postData = "{\"title\": \"My Title\", \"body\": \"My Body\", \"userId\": 1}"; byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); // Write post data to output stream try(OutputStream outputStream = httpURLConnection.getOutputStream()) { outputStream.write(postDataBytes, 0, postDataBytes.length); } // Get response code and response message int responseCode = httpURLConnection.getResponseCode(); String responseMessage = httpURLConnection.getResponseMessage(); // Process response if (responseCode == HttpURLConnection.HTTP_OK) { // Read response data BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); String responseData; StringBuilder responseBuilder = new StringBuilder(); while ((responseData = in.readLine()) != null) { responseBuilder.append(responseData); } in.close(); // Convert response to JSON object JSONObject jsonObject = new JSONObject(responseBuilder.toString()); System.out.println(jsonObject.toString()); } else { System.out.println("POST request failed: " + responseMessage); } // Disconnect httpURLConnection.disconnect(); ``` 在上面的代码中,我们使用HttpURLConnection类创建一个POST请求。我们将JSON对象作为POST数据传递,并将其写入输出流中。然后,我们读取响应并将其转换为JSON对象。 这是一个简单的例子,但你可以根据自己的需求定制它。记得在你的AndroidManifest.xml文件中添加Internet权限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值