java模拟post请求发送json的例子
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求,
方法一:
packagemain.utils;
importjava.io.*;
importjava.net.HttpURLConnection;
importjava.net.URL;
publicclassHttpUtilTest{
Loglog=newLog(this.getClass());//初始化日志类
/**
*@作用使用urlconnection
*@paramurl
*@paramParams
*@return
*@throwsIOException
*/
publicStringsendPost(Stringurl,StringParams)throwsIOException{
OutputStreamWriterout=null;
BufferedReaderreader=null;
Stringresponse="";
try{
URLhttpUrl=null;//HTTPURL类用这个类来创建连接
//创建URL
httpUrl=newURL(url);
//建立连接
HttpURLConnectionconn=(HttpURLConnection)httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("connection","keep-alive");
conn.setUseCaches(false);//设置不要缓存
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//POST请求
out=newOutputStreamWriter(
conn.getOutputStream());
out.write(Params);
out.flush();
//读取响应
reader=newBufferedReader(newInputStreamReader(
conn.getInputStream()));
Stringlines;
while((lines=reader.readLine())!=null){
lines=newString(lines.getBytes(),"utf-8");
response+=lines;
}
reader.close();
//断开连接
conn.disconnect();
log.info(response.toString());
}catch(Exceptione){
System.out.println("发送POST请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
}
catch(IOExceptionex){
ex.printStackTrace();
}
}
returnresponse;
}
}
方法二:使用httpclient实现
importjava.io.UnsupportedEncodingException;
importjava.net.URLEncoder;
importmain.utils.Log;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.ContentType;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.util.EntityUtils;
//post请求方法
publicStringsendPost(Stringurl,Stringdata){
Stringresponse=null;
log.info("url:"+url);
log.info("request:"+data);
try{
CloseableHttpClienthttpclient=null;
CloseableHttpResponsehttpresponse=null;
try{
httpclient=HttpClients.createDefault();
HttpPosthttppost=newHttpPost(url);
StringEntitystringentity=newStringEntity(data,
ContentType.create("text/json","UTF-8"));
httppost.setEntity(stringentity);
httpresponse=httpclient.execute(httppost);
response=EntityUtils
.toString(httpresponse.getEntity());
log.info("response:"+response);
}finally{
if(httpclient!=null){
httpclient.close();
}
if(httpresponse!=null){
httpresponse.close();
}
}
}catch(Exceptione){
e.printStackTrace();
}
returnresponse;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。