Source From Here
Question
I am working with a GET request made using Apache HttpComponents (v4- the latest version; not the older v3)... How do I obtain the mimetype of the response?
How-To
A fully sample code as below:
Question
I am working with a GET request made using Apache HttpComponents (v4- the latest version; not the older v3)... How do I obtain the mimetype of the response?
How-To
A fully sample code as below:
- package demo;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.URI;
- import java.util.List;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.protocol.HttpClientContext;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- public class GetDemo {
- public static void main(String[] args) throws Exception {
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try {
- HttpClientContext context = HttpClientContext.create();
- RequestConfig requestConfig = RequestConfig.custom()
- .setSocketTimeout(10000)
- .setConnectTimeout(10000)
- .build();
- HttpGet httpget1 = new HttpGet(args[0]);
- URI finalUrl = null;
- httpget1.setConfig(requestConfig);
- CloseableHttpResponse resp = httpclient.execute(httpget1, context);
- List
locations = context.getRedirectLocations(); - if (locations != null) {
- finalUrl = locations.get(locations.size() - 1);
- }
- int code = resp.getStatusLine().getStatusCode();
- String ct = resp.getEntity().getContentType().getValue(); // <--- get="" here="" mime="" span="" type=""> --->
- System.out.printf("Status code=%d (Content-type=%s)\n", code, ct);
- if(finalUrl!=null)
- {
- System.out.printf("%s\n", finalUrl);
- }
- else
- {
- System.out.printf("%s\n", args[0]);
- }
- BufferedReader br = new BufferedReader(new InputStreamReader((resp.getEntity().getContent())));
- if(ct.trim().contains("text/html"))
- {
- String line = null;
- while((line=br.readLine())!=null)
- {
- System.out.printf("%s\n", line);
- }
- }
- System.out.printf("===== DONE =====\n");
- resp.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- httpclient.close();
- }
- }
- }
沒有留言:
張貼留言