http post 请求raw(字符串请求)

HttpURLConnection

    //post字符串请求
    public String HttpPost(String url, String rawBody){

        HttpURLConnection conn = null;
        PrintWriter pw = null ;
        BufferedReader rd = null ;
        StringBuilder sb = new StringBuilder ();
        String line = null ;
        String response = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            pw = new PrintWriter(conn.getOutputStream());
            pw.print(rawBody);
            pw.flush();
            rd  = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = rd.readLine()) != null ) {
                sb.append(line);
            }
            response = sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(pw != null){
                    pw.close();
                }
                if(rd != null){
                    rd.close();
                }
                if(conn != null){
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

 fun postData1() {
        var url = "http://xxx:8082/basic-platform/schema/"
        var body = JSONObject()
        body.put("sn", "nlp_ai_capacity.xxxxx")
        body.put("query", "怎么办")
        var user_semantics = JSONObject()
        user_semantics.put("client_id", "orion.ovs.client.1514259512471")
        user_semantics.put("enterprise_id", "orion.ovs.entprise.2291039705")
        user_semantics.put("device_id", "nlp_ai_capacity_device")
        body.put("user_semantics", user_semantics)
        var json = body.toString()

        val thread: Thread = object : Thread() {
            override fun run() {
                super.run()
                try {
                    val post = HttpPostRaw().HttpPost(url, json)
                    println(post)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println(e.toString())
                }
            }
        }
        thread.start()
    }

HttpClients

public static String httpPostRaw(String url, String stringJson, Map<String,String> headers, String encode){
        String str="";
        if(encode == null){
            encode = "utf-8";
        }
        //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpost = new HttpPost(url);

        //设置header
        httpost.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson, encode);
        httpost.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            System.out.println(content);
            str=content;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }
    fun postData() {
        var url = "http://xxx/basic-platform/schema/"
        var body = JSONObject()
        body.put("sn", "nlp_ai_capacity.xxxxx")
        body.put("query", "怎么办")
        var user_semantics = JSONObject()
        user_semantics.put("client_id", "orion.ovs.client.1514259512471")
        user_semantics.put("enterprise_id", "orion.ovs.entprise.2291039705")
        user_semantics.put("device_id", "nlp_ai_capacity_device")
        body.put("user_semantics", user_semantics)
        var json = body.toString()

        val thread: Thread = object : Thread() {
            override fun run() {
                super.run()
                try {
                    HttpClientUtil.httpPostRaw(url, json, null, null)
                } catch (e: Exception) {
                    e.printStackTrace()
                    println(e.toString())
                }
            }
        }
        thread.start()
    }

xutils3 post

    fun getAnswer(ask: String) {
        var body = JSONObject()
        body.put("sn", "nlp_ai_capacity.xxxxx")
        body.put("query", ask)
        var user_semantics = JSONObject()
        user_semantics.put("client_id", "orion.ovs.client.1514259512471")
        user_semantics.put("enterprise_id", "orion.ovs.entprise.2291039705")
        user_semantics.put("device_id", "nlp_ai_capacity_device")
        body.put("user_semantics", user_semantics)
     
        var params = RequestParams("http://xxxx/basic-platform/schema/")
        params.addHeader("Content-Type", "application/json")
        params.bodyContent = body.toString()
        println(params.toJSONString())
        x.http().post(params, object : Callback.CommonCallback<String> {
            override fun onFinished() {
            }
            override fun onSuccess(result: String?) {
                if (result != null) {
                    var obj = JSONObject(result)
                }
            }
            override fun onCancelled(cex: Callback.CancelledException?) {
            }
            override fun onError(ex: Throwable?, isOnCallback: Boolean) {
            }
        })
    }

Cleartext HTTP traffic to xxx not permitted报错
在清单文件中的application中添加

      android:usesCleartextTraffic="true"

More than one file was found with OS independent path 'META-INF/DEPENDENCIES’报错
排除掉中间生成的重复DEPENDENCIES.txt文件

packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魑魅魍魉9527

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值