JAVA调用接口总结

哈哈 阅读:244 2022-05-18 12:10:13 评论:0
本文章主要介绍了JAVA调用接口,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!
  1. HttpUrlconnection部分
//发送JSON字符串 如果成功则返回成功标识。 
    public static String doJsonPost(String urlPath, String Json) { 
        // HttpClient 6.0被抛弃了 String result = ""; BufferedReader reader = null; try { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); // 设置文件类型: conn.setRequestProperty("Content-Type","application/json; charset=UTF-8"); // 设置接收类型否则返回415错误 //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415; conn.setRequestProperty("accept","application/json"); // 往服务器里面发送数据 if (Json != null && !TextUtils.isEmpty(Json)) { byte[] writebytes = Json.getBytes(); // 设置文件长度 conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length)); OutputStream outwritestream = conn.getOutputStream(); outwritestream.write(Json.getBytes()); outwritestream.flush(); outwritestream.close(); Log.d("hlhupload", "doJsonPost: conn"+conn.getResponseCode()); } if (conn.getResponseCode() == 200) { reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); result = reader.readLine(); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }

标签:java
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

我的关注

搜索
排行榜
关注我们