Examples of Java send get and POST request parameters

Source: Internet
Author: User
Tags finally block flush http request readline tostring stringbuffer

Example One

The code is as follows Copy Code

Package com.hongyuan.test;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.HttpURLConnection;
Import Java.net.URL;

public class HttpClient {
Send a GET request
public static string get (String path) throws exception{
HttpURLConnection Httpconn=null;
BufferedReader In=null;
try {
URL url=new url (path);
Httpconn= (HttpURLConnection) url.openconnection ();

Read response
if (Httpconn.getresponsecode () ==HTTPURLCONNECTION.HTTP_OK) {
StringBuffer content=new StringBuffer ();
String tempstr= "";
In=new BufferedReader (New InputStreamReader (Httpconn.getinputstream ()));
while ((Tempstr=in.readline ())!=null) {
Content.append (TEMPSTR);
}
return content.tostring ();
}else{
throw new Exception ("There is a problem with the request!");
}
catch (IOException e) {
E.printstacktrace ();
}finally{
In.close ();
Httpconn.disconnect ();
}
return null;
}
Send a GET request, Parameter form key1=value1&key2=value2 ...
public static string post (string path,string params) throws exception{
HttpURLConnection Httpconn=null;
BufferedReader In=null;
PrintWriter Out=null;
try {
URL url=new url (path);
Httpconn= (HttpURLConnection) url.openconnection ();
Httpconn.setrequestmethod ("POST");
Httpconn.setdoinput (TRUE);
Httpconn.setdooutput (TRUE);

  //Send POST request Parameters
   out=new printwriter (Httpconn.getoutputstream ());
   OUT.PRINTLN (params);
   Out.flush ();

  /Read response
   if (Httpconn.getresponsecode () ==httpurlconnection.http_ok) {
     stringbuffer content=new stringbuffer ();
    String tempstr= "";
    in=new BufferedReader (New InputStreamReader (Httpconn.getinputstream ()));
    while ((Tempstr=in.readline ())!=null) {
     content.append (TEMPSTR) ;
   }
    return content.tostring ();
  }else{
    throw new Exception ("There is a problem with the request!");
  }
 } catch (IOException e) {
   e.printstacktrace ();
 }finally{
   in.close ();
   out.close ();
   httpconn.disconnect ();
 }
  return null;
 }

public static void Main (string[] args) throws Exception {
String resmessage=httpclient.get ("Http://localhost:3000/hello?hello=hello get");
String resmessage=httpclient.post ("Http://localhost:3000/hello", "Hello=hello post");
System.out.println (Resmessage);
}

}


Example Two

HTTP Request Class

The code is as follows Copy Code

Package Wzh. Http;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;
Import Java.util.Map;

public class HttpRequest {
/**
* Request to send the Get method to the specified URL
*
* @param URL
* Send the requested URL
* @param param
* Request parameter, request parameter should be the form of name1=value1&name2=value2.
* @return The response result of the remote resource represented by the URL
*/
public static string Sendget (string url, string param) {
String result = "";
BufferedReader in = null;
try {
String urlnamestring = URL + "?" + param;
URL realurl = new URL (urlnamestring);
Opening and linking to URLs
URLConnection connection = Realurl.openconnection ();
To set common request properties
Connection.setrequestproperty ("Accept", "*/*");
Connection.setrequestproperty ("Connection", "keep-alive");
Connection.setrequestproperty ("User-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ");
Establish the actual connection
Connection.connect ();
Get all response header fields
map<string, list<string>> map = Connection.getheaderfields ();
Iterate through all the response header fields
For (String Key:map.keySet ()) {
SYSTEM.OUT.PRINTLN (key + "--->" + map.get (key));
}
Defines the response of a bufferedreader input stream to read a URL
in = new BufferedReader (New InputStreamReader (
Connection.getinputstream ()));
String Line;
while (line = In.readline ())!= null) {
result + = line;
}
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Send GET request exception!") "+ e);
E.printstacktrace ();
}
Use the finally block to close the input stream
finally {
try {
if (in!= null) {
In.close ();
}
catch (Exception E2) {
E2.printstacktrace ();
}
}
return result;
}

/**
* Request to send post method to specified URL
*
* @param URL
* Send the requested URL
* @param param
* Request parameter, request parameter should be the form of name1=value1&name2=value2.
* Response results for remote resources represented by the @return
*/
public static string Sendpost (string url, string param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realurl = new URL (URL);
Opening and linking to URLs
URLConnection conn = Realurl.openconnection ();
To set common request properties
Conn.setrequestproperty ("Accept", "*/*");
Conn.setrequestproperty ("Connection", "keep-alive");
Conn.setrequestproperty ("User-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ");
Send POST request must be set as follows two lines
Conn.setdooutput (TRUE);
Conn.setdoinput (TRUE);
Gets the output stream corresponding to the URLConnection object
out = new PrintWriter (Conn.getoutputstream ());
Send Request parameters
Out.print (param);
Buffer of flush output stream
Out.flush ();
Defines the response of a bufferedreader input stream to read a URL
in = new BufferedReader (
New InputStreamReader (Conn.getinputstream ()));
String Line;
while (line = In.readline ())!= null) {
result + = line;
}
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Send POST request exception!) "+e);
E.printstacktrace ();
}
Use the finally block to turn off the output stream, the input stream
finally{
try{
if (out!=null) {
Out.close ();
}
if (in!=null) {
In.close ();
}
}
catch (IOException ex) {
Ex.printstacktrace ();
}
}
return result;
}
}

Call Method:

  code is as follows copy code

    public static void Main (string[] args) {
  & nbsp;    //Send GET request
        String s= Httprequest.sendget ("http://localhost:6144/Home/RequestString", "key=123&v=456");
        System.out.println (s);
       
       //Send POST request
        String sr=httprequest.sendpost ("http://localhost:6144/Home/ Requestpoststring "," key=123&v=456 ");
        System.out.println (SR);
   }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.