java程序通过post方式请求servlet

阅读更多
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)