发布日期:2018-03-26
在java中如何发送HTTP请求,有没例子代码?+ 查看更多
在java中如何发送HTTP请求,有没例子代码?
+ 查看更多
发布日期:2018-03-08 17:54
分类:JAVA
浏览次数:76
在java中,如何组成一个HTTP请求消息并将其发送到HTTP服务器?
回答
你可以使用java.net.httpurlconnection。
例子(从这里),改进。包括在链接失效的情况下:
public static String executePost(String targetURL, String urlParameters) { HttpURLConnection connection = null; try { //Create connection URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream ( connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }