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 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 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 {
            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'
    }

你可能感兴趣的:(Android,java)