本文主要是介绍用Java发起HTTP请求与获取状态码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用Java请求Web程序比如访问WebService接口时,通常需要先判断访问URL的有效性,这里就Java发送HTTP请求的方式做简单记录,按照前辈们的说法,Java发HTTP请求,最常见的无非是两种,一种是用java.net.URLConnection,另一种则是大名鼎鼎的HttpClient。使用java.net.URLConnection比较麻烦,而HttpClient则比较简便。以发送POST请求为例
java.net.URLConnection方法如下:
private static void urlConnectionPost() {StringBuilder responseBuilder = null;BufferedReader reader = null;OutputStreamWriter wr = null;URL url;try {url = new URL("http://www.poorren.com");HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setDoOutput(true);conn.setConnectTimeout(1000 * 5);wr = new OutputStreamWriter(conn.getOutputStream());wr.write("");wr.flush();// Get the responsereader = new BufferedReader(new InputStreamReader(conn.getInputStream()));responseBuilder = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {responseBuilder.append(line + "\n");}wr.close();reader.close();System.out.println(responseBuilder.toString());} catch (IOException e) {e.printStackTrace();}
}
而获取状态码则只需在conn.connect();之后调用conn.getResponseCode();即可。
HttpClient方法:
private static void httpClientPost() {HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost("http://www.poorren.com");try {ContentProducer cp = new ContentProducer() {public void writeTo(OutputStream outstream) throws IOException {Writer writer = new OutputStreamWriter(outstream, "UTF-8");writer.write("");writer.flush();}};post.setEntity(new EntityTemplate(cp));HttpResponse response = client.execute(post);System.out.println(EntityUtils.toString(response.getEntity()));} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
}
使用HttpClient的情况下获取状态码直接在execute(post/get…)后获取即可。
这篇关于用Java发起HTTP请求与获取状态码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!