当前位置:编程学习 > JAVA >>

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://www.zzzyk.com /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();

}
}

 作者:feixiangdexin123087

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,