postjava_Java发送post⽅法详解总结⼀下java使⽤http发送post的⽅法:
1、post请求⽤于发送json 格式的参数:
/**
* post请求(⽤于请求json格式的参数)
*
* @param url 地址
* @param params json格式的参数
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = ateDefault();
HttpPost httpPost = new HttpPost( url );// 创建httpPost
httpPost.setHeader( "Accept", "application/json" );
httpPost.setHeader( "Content-Type", "application/json" );
String charSet = "UTF-8";
StringEntity entity = new StringEntity( params, charSet );
httpPost.setEntity( entity );
CloseableHttpResponse response = null;
try {
response = ute( httpPost );
StatusLine status = StatusLine();
int state = StatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = Entity();
String jsonString = String( responseEntity );
return jsonString;
} else {
<( "请求返回:" + state + "(" + url + ")" );
}
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2、⽤于发送key-value格式的参数
/**
* post请求(⽤于key-value格式的参数)
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params) { BufferedReader in = null;
try {
java valueof/
/ 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP⽅法
HttpPost request = new HttpPost();
request.setURI( new URI( url ) );
//设置参数
List nvps = new ArrayList();
for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) { String name = (String) ();
String value = String.valueOf( ( name ) );
nvps.add( new BasicNameValuePair( name, value ) );
//System.out.println(name +"-"+value);
}
request.setEntity( new UrlEncodedFormEntity( nvps, HTTP.UTF_8 ) ); HttpResponse response = ute( request );
int code = StatusLine().getStatusCode();
if (code == 200) { //请求成功
in = new BufferedReader( new InputStreamReader( Entity() .getContent(), "utf-8" ) );
StringBuffer sb = new StringBuffer( "" );
String line = "";
String NL = Property( "line.separator" );
while ((line = in.readLine()) != null) {
sb.append( line + NL );
}
in.close();
String();
} else { //
System.out.println( "状态码:" + code );
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
第三,发送get请求
/**
* get请求
*
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet( url );
HttpResponse response = ute( request );
/**请求发送成功,并得到响应**/
if (StatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = String( Entity() );
return strResult;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
以上所述是⼩编给⼤家介绍的Java发送post⽅法详解整合,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对脚本之家⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。