HttpClient 发送HTTP请求
需要Apache的三个包:
commons-httpclient-3.1.jar
commons-codec-1.9.jar
commons-logging.jar
没有自己在Apache官网下载,怎么导入就不多说了
代码如下:
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class MyTest {
/**
* HttpClient HTTP发送
*/
public static void main(String[] args) {
//定义发送状态
int statusCode = 0;
//定义响应接收流
InputStream in=null;
//
FileOutputStream fop = null;
//目标URL
String targetUrl = "http://localhost:8090/MyTest/index2.jsp";
try{
//定义HttpClient
HttpClient client = new HttpClient();
//Post模式提交
PostMethod method = new PostMethod(targetUrl);
//设置参数s
NameValuePair[] data = { new NameValuePair("name","leijianwei"),new NameValuePair("pwd","123456")};
//装入参数
method.setRequestBody(data);
//执行模式发送,并获取发送状态
statusCode = client.executeMethod(method);
//判断发送状态是否是200
if(statusCode == HttpStatus.SC_OK){
//获取服务端响应
in = method.getResponseBodyAsStream();
//fop =new FileOutputStream(new File(fileName));//存入文件
byte []binRead=new byte[1024];
int b = -1;
//循环读取流
while((b=in.read(binRead))!=-1){
//打印
String responseBody = new String(binRead,"utf-8");
System.out.println("打印出来吧:"+responseBody.trim());
//存入文件
//fop.write(binRead,0,b);
}
}else{
}
}catch(Exception e){
e.printStackTrace();
}
}
}