当前位置: 代码迷 >> Web前端 >> java中 发起请求到servlet 或许 Webservice
  详细解决方案

java中 发起请求到servlet 或许 Webservice

热度:467   发布时间:2012-07-03 13:37:43.0
java中 发起请求到servlet 或者 Webservice

HttpClient 发起请求到servlet 或者 Webservice


1.发送请求servlet,类似ajax异步调用

import java.net.HttpURLConnection;

public void do(){

String url =“http://localhost:8081/servlet.do”;
java.net.URL initStaticPageUrl = new java.net.URL(url);
java.net.HttpURLConnection httpConnection = (java.net.HttpURLConnection)initStaticPageUrl.openConnection();

httpConnection.getResponseCode();

}



2.java中 发送xml文件到servlet 或者 Webservice

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;

public void send(){

try{

String xmlpath = Main.homepath +"/oneword.xml";//xml文件保存路径

//读取xml文件
BufferedReader fin = new BufferedReader(new FileReader(xmlpath));
StringBuffer stringbuffer = new StringBuffer();
int k=0;
while(k != -1)
{
k = fin.read();
if(k != -1)
stringbuffer.append((char)k);
}
fin.close();

//发送oneword.xml文件
String xml = stringbuffer.toString();
String url2 = "
http://localhost:8081/word.html";
java.net.URL pageUrl = new java.net.URL(url2);
HttpURLConnection connection = (HttpURLConnection)pageUrl.openConnection();
connection.setRequestMethod( "POST" );
connection.setDoInput( true );
connection.setDoOutput( true );
connection.setRequestProperty( "Content-Type" , "text/xml" );
byte[] contentbyte = xml.getBytes();
connection.setRequestProperty( "Content-Length" , "" + contentbyte.length);
connection.setRequestProperty( "Cache-Control" , "no-cache" );
connection.setRequestProperty( "Pragma" , "no-cache" );
connection.setRequestProperty( "Expires" , "-1" );
OutputStream out=connection.getOutputStream();
out.write( contentbyte);
/**
OutputStreamWriter wout = new OutputStreamWriter(out,"UTF-8");
wout.write();
wout.flush();
**/
out.flush();
out.close();
   BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());  
   bis.close(); 
stringbuffer = null;
}catch(Exception e)
{
e.printStackTrace();
}

}

  相关解决方案