Android GET and POST Request

前端 未结 6 1718
执念已碎
执念已碎 2021-02-01 11:14

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is

6条回答
  •  -上瘾入骨i
    2021-02-01 12:01

    You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:

    import java.net.*;
    import java.io.*;
    public class SendPostRequest {
      public static void main(String[] args) throws MalformedURLException, IOException {
        URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
        HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
        String post = "this will be the post data that you will send"
        request.setDoOutput(true);
        request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
        request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
        request.setMethod("POST");
        request.connect();
        OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
        writer.write(post);
        writer.flush();
      }
    }
    

    A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:

    import java.net.*;
    import java.io.*;
    
    public class SendPostRequest {
      public static void main(String[] args) throws MalformedURLException, IOException {
        URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
        HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
        request.setMethod("GET");
        request.connect();
    
      }
    }
    

提交回复
热议问题