如何使用HttpURLConnection在java中通过post发送参数?

时间:2017-07-13 19:35:14

标签: java httprequest httpresponse

我无法使用HttpURLConnection通过java参数发送POST方法。我已经尝试了几种方法并进行了大量研究,但没有办法对我有用。我将保留下面的代码,以表明可以进行的修改。

$('#title').html(selected_article_title);

正如您所看到的,我尝试通过import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class HttpTeste { private final String USER_AGENT = "Mozilla/5.0"; public void sendPost(String url) throws Exception { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add request header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "idRoute=1"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } } 发送请求的参数,但它仍然无效。代码运行并且不会确认任何错误,但它不会返回应该返回的响应。 我还尝试通过urlParameters发送参数 但它也没有用,谢谢大家的合作!

1 个答案:

答案 0 :(得分:0)

是否必须使用HttpURLConnection?如果没有,您只想发送POST请求,我建议您使用OkHttp3