A brief introduction to HTTP requests in Java network programming
- 2020-04-01 04:10:40
- OfStack
Details of the HTTP request - the request line
GET in the request line is called the request mode, the request mode is: POST, GET, HEAD, OPTIONS, DELETE, TRACE, PUT, common: GET, POST
If the user does not set it, the browser will send the server a get request by default, such as direct input address access in the browser, click the hyperlink access, and so on. If the user wants to change the request mode to post, he can change the submission mode of the form.
Both POST and GET are used to request a WEB resource from the server. The difference between the two methods is mainly reflected in the data transmission: if the request mode is GET, the URL address of the request can be followed by ? Is the form with the data given to the server, and the multiple data are separated by &, for example: GET /mail/1.html? Name = abc&password = xyz HTTP / 1.1
GET features: the parameters attached to the URL address are limited, and the data capacity is usually not more than 1K.
If the request mode is POST, data can be sent to the server in the entity content of the request.
The details of the HTTP request -- the message header
Common headers in HTTP requests
Accept: the browser tells the server through this header which data types it supports
Accept-charset: this header lets the browser tell the server which character set it supports
Accept-encoding: the browser tells the server, via this header, which compression format is supported
Accept-language: the browser tells the server its locale through this header
Host: the browser tells the server through this header which Host it wants to access
If-modified-since: the browser tells the server via this header how long the data has been cached
Referer: this header tells the server which page the client came from. Preventing hotlinking
Connection: the browser tells the server via this header whether to break or hold the Connection after the request
Ex. :
http_get
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Http_Get {
private static String URL_PATH = "http://192.168.1.125:8080/myhttp/pro1.png";
public Http_Get() {
// TODO Auto-generated constructor stub
}
public static void saveImageToDisk() {
InputStream inputStream = getInputStream();
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("C:\test.png");
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static InputStream getInputStream() {
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(URL_PATH);
if (url != null) {
httpURLConnection = (HttpURLConnection) url.openConnection();
//Sets the timeout for connecting to the network
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
//Set the HTTP request to use GET
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
//Get an input stream from the server
inputStream = httpURLConnection.getInputStream();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
public static void main(String[] args) {
//Get the image from the server and save it locally
saveImageToDisk();
}
}
Http_Post
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class Http_Post {
//Request the url on the server side
private static String PATH = "http://192.168.1.125:8080/myhttp/servlet/LoginAction";
private static URL url;
public Http_Post() {
// TODO Auto-generated constructor stub
}
static {
try {
url = new URL(PATH);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String sendPostMessage(Map<String, String> params,
String encode) {
//The string initialized as a StringBuffer
StringBuffer buffer = new StringBuffer();
try {
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
//Complete transcoding operation
buffer.append(entry.getKey()).append("=").append(
URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
buffer.deleteCharAt(buffer.length() - 1);
}
// System.out.println(buffer.toString());
//Remove the last &
System.out.println("-->>"+buffer.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);//Represents getting data from the server
urlConnection.setDoOutput(true);//Represents writing data to the server
//Gets the byte size and length of the uploaded information
byte[] mydata = buffer.toString().getBytes();
//The type that represents the body of the setup request is a text type
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length",
String.valueOf(mydata.length));
//Get an output stream that outputs data to the server
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(mydata,0,mydata.length);
outputStream.close();
//Get the results and status codes of the server response
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
return changeInputStream(urlConnection.getInputStream(), encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String changeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray(), encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "123");
String result = Http_Post.sendPostMessage(params, "utf-8");
System.out.println("--result->>" + result);
}
}