编程语言
首页 > 编程语言> > Java 给python发送post请求

Java 给python发送post请求

作者:互联网

直接上代码

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/x-javascript->json");
         // 设置接收类型否则返回415错误
         //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
         conn.setRequestProperty("accept","application/json");
         conn.connect();
         // 往服务器里面发送数据
         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("ddddd","responseCode"+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;
   }

参考:https://blog.csdn.net/caidi1988314/article/details/72916165/

标签:Java,String,outwritestream,python,Json,setRequestProperty,reader,post,conn
来源: https://blog.csdn.net/weixin_41619057/article/details/95958785