比如说一个SERVLET的地址是
http://www.sina.com.cn/test/servlet
(这个SERVLET是我自己可以修改的)
现在我这里的程序要测试这个连结是否正常
我在JAVA里面的程序应该怎么写才好?
这个还有跨域的问题,不能用AJAX去试
我想在JAVA里面测试
7条回答 默认 最新
- fireinjava 2011-08-02 08:43关注
redstarofsleep的没错,我来个完整的
[code="java"]
import java.io.IOException;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;public class HttpSender {
public String send(String url, String request) throws Exception { String response = null; HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod(url); method.addRequestHeader("charset", "GBK"); method.addRequestHeader("content-type", "application/x-www-form-urlencoded"); method.setRequestEntity(new StringRequestEntity(request, null, "GBK")); try { int retcode = httpClient.executeMethod(method); if (retcode == HttpStatus.SC_OK) { byte[] responseBody = new byte[10240]; java.io.InputStream istream = method.getResponseBodyAsStream(); int npos = 0; int nread = 0; while ((nread = istream.read(responseBody, npos, responseBody.length - npos)) >= 0) { npos += nread; if (npos >= responseBody.length) { byte[] tmpBuf = new byte[npos + 51200]; System.arraycopy(responseBody, 0, tmpBuf, 0, npos); responseBody = tmpBuf; } } response = new String(responseBody, 0, npos); } else { throw new IOException("发送失败: retcode: " + retcode); } method.releaseConnection(); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { String reqStr = "<?xml version=\"1.0\" encoding=\"GBK\"?><request><params><param><curDate>20101010</curDate></param></params></request>"; HttpSender sender = new HttpSender(); String reponse = sender.send("http://www.sina.com.cn/test/servlet", reqStr); System.out.println("返回报文"+reponse); }
}
[/code]
当然,你的web.xml要配置
[code="java"]
servlet
com.xx.YourServlet<servlet-mapping> <servlet-name>servlet</servlet-name> <url-pattern>/servlet</url-pattern> </servlet-mapping>
[/code]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报