java中發起請求到servlet或者Webservice – JAVA編程語言程序開發技術文章

HttpClient 發起請求到servlet 或者 Webservice

1.發送請求servlet,類似ajax異步調用
import java.net.HttpURLConnection;
public void do(){
String url =“https://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 = "https://www.aiwalls.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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。