1、传参形式
public static String sendPostRequest(String url, String postStr) {
String result = "";
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
HttpMethodParams params = method.getParams();
params.setContentCharset("UTF-8");
method.addParameter("requesttype", requestType);
if (!StringUtil.isEmpty(postStr)) {
method.addParameter("data", postStr);
}
client.getHttpConnectionManager().getParams().setConnectionTimeout(100000);
client.getHttpConnectionManager().getParams().setSoTimeout(100000);
method.getParams().setParameter("http.socket.timeout", 100000);
int status = client.executeMethod(method);
if (status == 200) {
result = method.getResponseBodyAsString();
}
method.releaseConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
2、json
public static String postURL(String address, String postStr, String encode) {
String rec_string = "";
URL url = null;
HttpURLConnection urlConn = null;
try {
url = new URL(address);
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setConnectTimeout(30000);
urlConn.setReadTimeout(30000);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConn.setRequestProperty("accept", "application/json");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream(), encode);
out.write(postStr);
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), encode));
StringBuffer sb = new StringBuffer();
int ch;
while((ch = rd.read()) > -1) {
sb.append((char)ch);
}
rec_string = sb.toString().trim();
rd.close();
} catch (Exception var13) {
rec_string = "-107";
} finally {
if (urlConn != null) {
urlConn.disconnect();
}
}
return rec_string;
}
传递json的另一种写法:
public String doPost(String url, String jsonStr) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String result = "";
try {
StringEntity s = new StringEntity(jsonStr);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if (res.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(res.getEntity());
}
} catch (Exception var8) {
var8.printStackTrace();
}
return result;
}