java類(客戶端)接收servlet返回值

//測試類以下java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
 
public class ClientTest {
    //定義servlet路徑,MyServlet是工程名字,本身能夠修改
    private static String path="http://localhost:8080/MyServlet/QueryServlet";
     
    public static void main(String[] args) throws Exception {
       URL url =new URL(path);
       //接收servlet返會值,是字節
       InputStream is=url.openStream();
       
       //因爲is是字節,因此咱們要把它轉換爲String類型,不然遇到中文會出現亂碼
       BufferedReader reader=new BufferedReader(new InputStreamReader(is));
       StringBuffer sb=new StringBuffer();
       String line=null;
       while((line=reader.readLine())!=null){
           sb.append(line+"\n");
       }
       //輸出servlet返回值
       System.out.println(sb);
    }
 
}

//servlet類以下:app

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class QueryServlet extends HttpServlet{
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet");
        doPost(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");
         
        //解決亂碼問題,必須放在最前面
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
         
        //接收穿過來的值
        //req.getAttribute(arg0);
         
        PrintWriter out=resp.getWriter();
        //content能夠servlet訪問方法返回的值
        String content="我愛祖國天安門";
        //返回值到客戶端
        out.write(content);
         
     
    }
 
}
相關文章
相關標籤/搜索