Apache 的HttpClient 提供很多工具让开发者使用,其中常用的一种是调用http的请求,下面代码就是模拟了http的post和get请求。
package cn.tang.test.demo.httpclient;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class TestInvoke {
private static final String host ="10.1.1.225";
// private static final String host ="localhost";
public static void main(String[] args) {
try {
get();
post();
get2();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void post() {
String url = "http://"+host+":8080/method/invoke";
PostMethod method = new PostMethod(url);
NameValuePair[] data = {
new NameValuePair("key", "39d7e330-d271-4fe8-904a-aaf872962431"),
new NameValuePair("invokeMethod", "messageReceive"),
new NameValuePair("jsonData", "messageReceive") };
method.setRequestBody(data);
execute(method);
}
public static void get2() {
String url = "http://"+host+":8080/method/invoke?key=39d7e330-d271-4fe8-904a-aaf872962431&invokeMethod=messageReceive&jsonData=data";
GetMethod method = new GetMethod(url);
execute(method);
}
public static void get() {
String url = "http://"+host+":8080/method/list";
GetMethod method = new GetMethod(url);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
execute(method);
}
private static void execute(HttpMethod method) {
try {
HttpClient client = new HttpClient();
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
代码很简单,就不加注释和解释了。