Java发送post方法详解
总结一下java使用http发送post的方法:
1、post请求用于发送json格式的参数:
/** *post请求(用于请求json格式的参数) * *@paramurl地址 *@paramparamsjson格式的参数 *@return */ publicstaticStringdoPost(Stringurl,Stringparams)throwsException{ CloseableHttpClienthttpclient=HttpClients.createDefault(); HttpPosthttpPost=newHttpPost(url);//创建httpPost httpPost.setHeader("Accept","application/json"); httpPost.setHeader("Content-Type","application/json"); StringcharSet="UTF-8"; StringEntityentity=newStringEntity(params,charSet); httpPost.setEntity(entity); CloseableHttpResponseresponse=null; try{ response=httpclient.execute(httpPost); StatusLinestatus=response.getStatusLine(); intstate=status.getStatusCode(); if(state==HttpStatus.SC_OK){ HttpEntityresponseEntity=response.getEntity(); StringjsonString=EntityUtils.toString(responseEntity); returnjsonString; }else{ logger.error("请求返回:"+state+"("+url+")"); } }finally{ if(response!=null){ try{ response.close(); }catch(IOExceptione){ e.printStackTrace(); } } try{ httpclient.close(); }catch(IOExceptione){ e.printStackTrace(); } } returnnull; }
2、用于发送key-value格式的参数
/** *post请求(用于key-value格式的参数) * *@paramurl *@paramparams *@return */ publicstaticStringdoPost(Stringurl,Mapparams){ BufferedReaderin=null; try{ //定义HttpClient HttpClientclient=newDefaultHttpClient(); //实例化HTTP方法 HttpPostrequest=newHttpPost(); request.setURI(newURI(url)); //设置参数 Listnvps=newArrayList (); for(Iteratoriter=params.keySet().iterator();iter.hasNext();){ Stringname=(String)iter.next(); Stringvalue=String.valueOf(params.get(name)); nvps.add(newBasicNameValuePair(name,value)); //System.out.println(name+"-"+value); } request.setEntity(newUrlEncodedFormEntity(nvps,HTTP.UTF_8)); HttpResponseresponse=client.execute(request); intcode=response.getStatusLine().getStatusCode(); if(code==200){//请求成功 in=newBufferedReader(newInputStreamReader(response.getEntity() .getContent(),"utf-8")); StringBuffersb=newStringBuffer(""); Stringline=""; StringNL=System.getProperty("line.separator"); while((line=in.readLine())!=null){ sb.append(line+NL); } in.close(); returnsb.toString(); }else{// System.out.println("状态码:"+code); returnnull; } }catch(Exceptione){ e.printStackTrace(); returnnull; } }
第三,发送get请求
/** *get请求 * *@return */ publicstaticStringdoGet(Stringurl){ try{ HttpClientclient=newDefaultHttpClient(); //发送get请求 HttpGetrequest=newHttpGet(url); HttpResponseresponse=client.execute(request); /**请求发送成功,并得到响应**/ if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ /**读取服务器返回过来的json字符串数据**/ StringstrResult=EntityUtils.toString(response.getEntity()); returnstrResult; } }catch(IOExceptione){ e.printStackTrace(); } returnnull; }
以上所述是小编给大家介绍的Java发送post方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!