【问题标题】:How to get the response body and how to set the request body with HttpURLConnection class?如何获取响应正文以及如何使用 HttpURLConnection 类设置请求正文?
【发布时间】:2020-02-12 03:33:46
【问题描述】:

我正在使用 c# 和 Xamarin.Android。
我的问题可能不是很标准,因为它没有任何代码。但我只想知道 HttpURLConnection 类提供了什么。
众所周知,一个http/https请求有请求头、请求体、响应头和响应体。
但是我觉得HttpURLConnection这个类还是太抽象了。InputStream和OutputStream是什么(或者Android文档中的getInputStream和getOutputStream方法)?
Microsoft 文档刚刚告诉我这是 System.IO.Stream,什么都没有。Android 文档告诉我这些方法返回 InputStream 或 OutputStream。
我不知道 InputStream 和 OutputStream 是不是 Java 中非常重要的概念。如果是,请告诉我如果我调用它们的 ToString 方法会发生什么。我只想知道如何获取响应正文以及如何设置请求正文。
如果您使用的不是c#而是Java开发Android App,您也可以帮助我!告诉我我应该使用什么方法(在Java中),我将能够在Microsoft doc中找到它。
请帮忙!我会在这里等。

PS:文章部分内容是机器翻译的,包括这句话。

【问题讨论】:

    标签: c# android xamarin


    【解决方案1】:

    这是一个简单的例子,Java 使用HttpURLConnection,你可以参考它,然后转换成C#:

    URL url = new URL("http://*******");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("POST");
    //set request body
    OutputStream os = httpCon.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
    osw.write("Just Some Text");
    osw.flush();
    osw.close();
    os.close();  //don't forget to close the OutputStream
    httpCon.connect();
    
    //read the response
    String result;
    BufferedInputStream bis = new BufferedInputStream(httpCon.getInputStream());
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result2 = bis.read();
    while(result2 != -1) {
        buf.write((byte) result2);
        result2 = bis.read();
    }
    result = buf.toString();
    System.out.println(result);
    

    【讨论】:

    • 对不起,我当时正在关闭我的程序。
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多