URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");// 提交模式 conn.setDoOutput(true);// 是否输入参数 StringBuffer params = new StringBuffer(); // 表单参数与get形式一样 params.append("user").append("=").append("111").append("&") .append("password").append("=").append("111"); byte[] bypes = params.toString().getBytes(); conn.getOutputStream().write(bypes);// 输入参数 InputStream inStream=conn.getInputStream(); String mes = new String(StreamTool.readInputStream(inStream), "gbk"); JSONObject jsonToken = JSONObject.fromObject(mes); System.out.println(jsonToken.get("token")); System.out.println(StreamTool.readInputStream(inStream));
读取输入流数据
import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { /** * 从输入流中读取数据 * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = inStream.read(buffer)) !=-1 ){ outStream.write(buffer, 0, len); } byte[] data = outStream.toByteArray();//网页的二进制数据 outStream.close(); inStream.close(); return data; } }