Method of mutual invocation between two Java projects

Source: Internet
Author: User

If you have two Java projects, how to communicate information to each other
Premise: You must know the IP address and access path of the server to which you want to communicate the Java project (receiving requester).
In fact, the communication between the two Java projects is still a request using HTTP. There are two main ways of doing this:
① uses Apache's httpclient approach.
② uses the HttpURLConnection method under the java.net package that comes with the JDK.

This time the main explanation httpurlconnection way:
HttpURLConnection delivery requests are commonly used in two ways: Post and get. Use the Setrequestmethod () method to set how the pass is passed.
①, use post to pass the request:
The first app (the server that sends the HTTP request):
Create a Servlet_test1.java file under Com.servlet

Package com.servlet;

Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Servlet_test1 extends HttpServlet {


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Set the encoding of the request
Request.setcharacterencoding ("Utf-8");
Setting the encoding when returning
Response.setcontenttype ("Text/html;charset=utf-8");
System.out.println ("Test1");
Set the URL address of the HTTP connection, which is the URL of the second app. If you are not on the same computer, you can turn 127.0.0.1 to the appropriate IP address
String http= "Http://127.0.0.1:8080/test2/Setvlet_test2";
URL url=new url (http);
Generating HttpURLConnection connections
HttpURLConnection httpurlconnection= (httpurlconnection) url.openconnection ();
The output stream is set, the default is False, and the parameter cannot be passed.
Httpurlconnection.setdooutput (TRUE);
Sets the way the request is sent. Note: Be sure to capitalize
Httpurlconnection.setrequestmethod ("POST");
Sets the time when the connection times out. But not set, in the case of network anomalies, may cause the program zombie and cannot continue to execute downward, so the general set a time-out. Unit is milliseconds
Httpurlconnection.setconnecttimeout (30000);
Sets the output stream.
OutputStreamWriter writer=new OutputStreamWriter (Httpurlconnection.getoutputstream (), "utf-8");
Pass the parameters, middle use & symbol segmentation.
Writer.write ("username=123&password=456");
Used to flush the buffered stream. Because the default she will write to the memory buffer stream, to a certain amount of data, will be written, use this command can let him write immediately, or the next to close the stream
Writer.flush ();
Used to close the output stream, so it is not possible to output data after it has been closed, so flushing the buffer stream with flush
Writer.close ();
Get the return request.
int Responsecode=httpurlconnection.getresponsecode ();
Indicates a successful request
if (RESPONSECODE==HTTPURLCONNECTION.HTTP_OK) {
System.out.println ("OK" +responsecode);
Gets the output stream for the server. Get the data returned
InputStream Urlstream=httpurlconnection.getinputstream ();
BufferedReader reader=new BufferedReader (New InputStreamReader (Urlstream));
String Line;
String tline= "";
while ((Line=reader.readline ())!=null) {
Tline+=line;
}
Output all the data
System.out.println (Tline);
}else{
System.out.println ("ERR" +responsecode);
}


}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
This.doget (request, response);
}

}
Configuration servlet in the Web. xml file in the Test1 project:
<servlet>
<servlet-name>Servlet_test1</servlet-name>
<servlet-class>com.servlet.Servlet_test1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet_test1</servlet-name>
<url-pattern>/Servlet_test1</url-pattern>
</servlet-mapping>

Code on the server side (receiving HTTP requester)
Create a Servlet_test2.java file under the Com.servlet package under the Test2 project
Package com.servlet;

Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Setvlet_test2 extends HttpServlet {


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Request.setcharacterencoding ("Utf-8");
Response.setcontenttype ("Text/html;charset=utf-8");
System.out.println ("Test2");
System.out.println (Request.getparameter ("username"));
System.out.println (Request.getparameter ("password"));
Get parameters for sending HTTP requests
String Username=request.getparameter ("username");
String password=request.getparameter ("password");
Returning response data to the HTTP sender
if ("123". Equals (username) && "456". Equals (password)) {
Response.getwriter (). Write ("{\" falg\ ": \" Success\ "}");
}else{
Response.getwriter (). Write ("{\" falg\ ": \" Error\ "}");
}

}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
This.doget (request, response);
}

}
The configuration in the Web. xml file for the Test2 project is as follows:
<servlet>
<servlet-name>Setvlet_test2</servlet-name>
<servlet-class>com.servlet.Setvlet_test2</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Setvlet_test2</servlet-name>
<url-pattern>/Setvlet_test2</url-pattern>
</servlet-mapping>

Enter HTTP://LOCALHOST:8080/TEST1/SERVLET_TEST1 in the Address bar.
It will output:
Test1
Test2
123
456
OK200
{"Falg": "Success"}

Here are a few things to note:
1. Send request by default is Get mode.
2. In the sender, OutputStream must be before inptstream. Otherwise, an exception will be thrown
3. An HTTP request consists of two parts: one is the message header information and the other is the body.

Method of mutual invocation between two Java projects

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.