简体   繁体   中英

How to get the response body and how to set the request body with HttpURLConnection class?

I am using c# and Xamarin.Android.
My question may not be very standard,because it doesn't have any code.But I just want to know what's the HttpURLConnection class provides.
As everyone knows, an http/https request has request header, request body, response header, and response body.
But I think HttpURLConnection class is still too abstract.What's InputStream and OutputStream(or getInputStream and getOutputStream method in Android document)?
Microsoft document just told that's System.IO.Stream, like nothing.Android doc told me these method return InputStream or OutputStream.
I don't know if InputStream and OutputStream are very important concepts in Java.If they're, please tell me what'll happen if I call their ToString method.And I just want know how to get the response body and how to set the request body.
If you're using not c# but Java to develop Android App, you can also help me!Just tell me what method should I use(In Java), and I will be able to find it in Microsoft doc.
Please help!I'll wait here.

PS:Some parts of the article is translated by machine, include this sentence.

Here is a simple sample that using HttpURLConnection by Java.you could refer to it,and then convert to 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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