欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java程序通过post方式请求servlet

程序员文章站 2022-04-24 17:21:44
...
package util;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.URL;

public class RemotingUtil {
	
	private static final String CHAR_SET = "UTF-8";
	
	private static final String URL = "http://192.168.112.181/baas/FabricInvokeServlet";
	
	public static String remtoingResponseData(String url, String psotData) {
		String data = null;
        try {
            URL dataUrl = new URL(url);
            HttpURLConnection con = (HttpURLConnection) dataUrl.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setReadTimeout(10000);
            
            StringBuilder body = new StringBuilder();
            body.append("params=");
            body.append(URLEncoder.encode(psotData, CHAR_SET));
 
            String s = body.toString();
            
            OutputStream os = con.getOutputStream();
            os.write(s.getBytes(CHAR_SET));
            os.flush();
            os.close();
 
            InputStream is = con.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            byte d[] = new byte[dis.available()];
            dis.read(d);
            data = new String(d);
            con.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return data;
	}

}
相关标签: servlet java post