简体   繁体   English

如何在android上使用java发出http post请求

[英]How can I make an http post request using java on android

How can I hit an api post end point using java and pass a body as a json data ?如何使用 java 到达 api post 端点并将正文作为 json 数据传递?

I found this code on the android docs but I don't know how to pass the request body我在 android 文档上找到了这段代码,但我不知道如何传递请求正文

 URL url = new URL("http://www.android.com/");
 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
 try {
   urlConnection.setDoOutput(true);
   urlConnection.setChunkedStreamingMode(0);
   OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
   writeStream(out);

   InputStream in = new BufferedInputStream(urlConnection.getInputStream());
   readStream(in);
} finally {
   urlConnection.disconnect();
}

I use http client and it goes really well, (unless you send a delete call with body).我使用 http 客户端,它运行得非常好,(除非您发送带有正文的删除调用)。

Here you have all the info you need to import it and get it done.在这里,您拥有导入并完成它所需的所有信息。

How to import "HttpClient" to Eclipse? 如何将“HttpClient”导入 Eclipse?

With this you can get your call running if you have problems building the thing with httpClient, send your code in this question and i will try to help.有了这个,如果您在使用 httpClient 构建东西时遇到问题,您可以让您的呼叫运行,在这个问题中发送您的代码,我会尽力提供帮助。

I am kotlin Guy but this is how I have done post request in java我是 kotlin Guy,但这就是我在 Java 中完成发布请求的方式

new Thread(() -> {
    try {
        URL url = new URL("http://www.android.com/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        DataOutputStream requestWriter = new DataOutputStream(connection.getOutputStream());
        requestWriter.writeBytes(JsonBodyObject.toString());
        requestWriter.close();
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseData = responseReader.readLine();
        activity.runOnUiThread(() -> {
            try {
                JSONObject json = new JSONObject(responseData);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        });
        responseReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM