龙空技术网

JAVA对web发起POST请求

最后一个NPE 530

前言:

现在朋友们对“javapost发送”大致比较讲究,我们都想要剖析一些“javapost发送”的相关资讯。那么小编同时在网上网罗了一些关于“javapost发送””的相关文章,希望小伙伴们能喜欢,咱们快快来学习一下吧!

public static void main(String[] args) throws IOException { System.err.println( WebUtil.sendPost("","params1=123&params=56",null));}public static String sendPost(String url,String param,HashMap<String,String> requestHead) throws IOException { URL url1=new URL(url); URLConnection connection=url1.openConnection(); connection.setRequestProperty("Connection","Keep-Alive"); if(requestHead==null){ }else{ for(String key:requestHead.keySet()){ connection.setRequestProperty(key,requestHead.get(key)); } } connection.setDoInput(true); connection.setDoOutput(true); PrintWriter printWriter=new PrintWriter(connection.getOutputStream()); printWriter.write(param); printWriter.flush(); InputStream inputStream=connection.getInputStream(); int len=0; ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); byte[] bytes=new byte[024]; while((len=inputStream.read(bytes))!=-1){ outputStream.write(bytes); } String ret=new String(outputStream.toByteArray()); String charset=getWebCharset(ret); return new String(outputStream.toByteArray(),charset);}

其中要注意最重要的两行:

connection.setDoInput(true); connection.setDoOutput(true);

运行结果:

params1||{123}

params||{56}

标签: #javapost发送