Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseMessage.

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:com.googlecode.jmxtrans.model.output.support.HttpOutputWriter.java

@Override
public void doWrite(Server server, Query query, Iterable<Result> results) throws IOException {
    HttpURLConnection httpURLConnection = createHttpURLConnection();
    try {// w w  w .  jav  a 2  s  .c  om
        configurer.configure(httpURLConnection);

        writeResults(server, query, results, httpURLConnection);

        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn("Failure {}:'{}' to send result to server '{}' with proxy {}", responseCode,
                    httpURLConnection.getResponseMessage(), url, proxy);
        }
        if (logger.isTraceEnabled()) {
            logger.trace(IOUtils.toString(httpURLConnection.getInputStream()));
        }
    } finally {
        consumeInputStreams(httpURLConnection);
    }
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

private void readResponse(HttpURLConnection http, AdaptrisMessage reply) throws IOException, CoreException {
    int responseCode = http.getResponseCode();
    logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    log.trace("Content-Length is " + http.getContentLength());

    if (responseCode < 200 || responseCode > 299) {
        if (ignoreServerResponseCode()) {
            log.trace("Ignoring HTTP Reponse code {}", responseCode);
            processErrorReply(http, reply);
            return;
        } else {/*  w  ww.  ja  va2s . c o m*/
            throw new ProduceException("Failed to send payload, got " + responseCode);
        }
    }
    if (getEncoder() != null) {
        copy(getEncoder().readMessage(http), reply);
    } else {
        processReply(http, reply);
    }
}

From source file:org.callimachusproject.test.WebResource.java

public void post() throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(false);/*from  w w w .j  a  v a 2s .com*/
    Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode());
}

From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java

/**
 * Sends a POST request with an attached object
 * @param url the url that should be opened
 * @param params the body parameters/*w w w .j  a v a2 s  . c om*/
 * @param attachment the object to be attached
 * @return the response
 * @throws IOException
 */
public static String postWithAttachment(String url, Map<String, String> params, Object attachment)
        throws IOException {
    String boundary = generateBoundaryString(10);
    URL servUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB);
    conn.setRequestMethod("POST");
    String contentType = "multipart/form-data; boundary=" + boundary;
    conn.setRequestProperty("Content-Type", contentType);

    byte[] body = generatePostBody(params, attachment, boundary);

    conn.setDoOutput(true);
    conn.connect();
    OutputStream out = conn.getOutputStream();
    out.write(body);
    InputStream is = null;
    try {
        is = conn.getInputStream();
    } catch (FileNotFoundException e) {
        is = conn.getErrorStream();
    } catch (Exception e) {
        int statusCode = conn.getResponseCode();
        Log.e("Response code", "" + statusCode);
        return conn.getResponseMessage();
    }

    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String l;
    while ((l = r.readLine()) != null)
        sb.append(l).append('\n');
    out.close();
    is.close();
    if (conn != null)
        conn.disconnect();
    return sb.toString();
}

From source file:com.ngdata.hbaseindexer.util.solr.SolrTestingUtility.java

/**
 * Creates a new core, associated with a collection, in Solr.
 *///  www  .j  a  v  a  2 s . com
public void createCore(String coreName, String collectionName, String configName, int numShards, String dataDir)
        throws IOException {
    String url = "http://localhost:" + solrPort + "/solr/admin/cores?action=CREATE&name=" + coreName
            + "&collection=" + collectionName + "&configName=" + configName + "&numShards=" + numShards;

    if (dataDir != null) {
        url += "&dataDir=" + dataDir;
    }

    URL coreActionURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) coreActionURL.openConnection();
    conn.connect();
    int response = conn.getResponseCode();
    conn.disconnect();
    if (response != 200) {
        throw new RuntimeException("Request to " + url + ": expected status 200 but got: " + response + ": "
                + conn.getResponseMessage());
    }
}

From source file:org.callimachusproject.test.WebResource.java

private WebResource findLink(String rel, boolean rev, String... types)
        throws IOException, MalformedURLException, ProtocolException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("OPTIONS");
    Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode());
    for (Map.Entry<String, List<String>> e : con.getHeaderFields().entrySet()) {
        if (!"Link".equalsIgnoreCase(e.getKey()))
            continue;
        for (String header : e.getValue()) {
            Assert.assertNotNull(header);
            Matcher m = LINK.matcher(header);
            while (m.find()) {
                if (rev && !header.contains("rev="))
                    continue;
                String href = m.group(1);
                String a = m.group(2);
                String r = m.group(3) != null ? m.group(3) : m.group(4);
                String t = m.group(5) != null ? m.group(5) : m.group(6);
                if (a != null && !TermFactoryImpl.newInstance(uri).resolve(a).equals(uri))
                    continue;
                if (!rel.equals(r))
                    continue;
                if (types.length == 0 || t == null)
                    return ref(href);
                for (String type : types) {
                    for (String t1 : t.split("\\s+")) {
                        if (t1.length() > 0 && t1.startsWith(type)) {
                            return ref(href);
                        }/* w w  w.j a  va 2  s. c o m*/
                    }
                }
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<").append(uri).append("?").append(rel);
    sb.append(">");
    if (rev) {
        sb.append("; rev=\"");
    } else {
        sb.append("; rel=\"");
    }
    sb.append(rel).append("\"; type=\"");
    for (String type : types) {
        sb.append(type).append(' ');
    }
    sb.setLength(sb.length() - 1);
    sb.append("\"");
    Assert.assertEquals(sb.toString(), con.getHeaderField("Link"));
    return null;
}

From source file:com.mfast.evaluations.DCAppSession.java

/**
 * Request send to DCApp// ww w  . j  a  v  a2  s  .  c o  m
 * @return
 * @throws Exception 
 */
public String sendGet() throws Exception {
    String url = null;
    //StringBuilder urlSB = new StringBuilder("http://localhost:55780/runtests?testid=");
    StringBuilder urlSB = new StringBuilder("http://");
    urlSB.append(request.getDCAppServerIp());
    urlSB.append(":55780/runtests?testid=");
    urlSB.append(request.getTestId());
    urlSB.append("&level=");
    urlSB.append(request.getLevel());
    urlSB.append("&position=");
    urlSB.append(request.getPosition());
    urlSB.append("&patientId=");
    urlSB.append(request.getPatientId());
    urlSB.append("&patientHeight=");
    urlSB.append(request.getPatientHeight());
    urlSB.append("&patientGender=");
    urlSB.append(request.getPatientGender());
    urlSB.append("&sessionId=");
    urlSB.append(sessionId);
    urlSB.append("&weight=");
    urlSB.append(request.getWeight());
    urlSB.append("&showResults=");
    urlSB.append(request.getShowResults());
    url = urlSB.toString();

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    String msg = con.getResponseMessage();
    System.out.println("response message " + msg);
    System.out.println("\nSending 'GET' request to URL : " + url);
    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();

    return response.toString();
}

From source file:sdmx.net.service.knoema.KnoemaRESTServiceRegistry.java

private StructureType retrieve2(String urlString) throws MalformedURLException, IOException, ParseException {
    System.out.println("Retrieve:" + urlString);
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }//from   ww w  . jav  a2  s .com
    InputStream in = conn.getInputStream();
    //FileOutputStream temp = new FileOutputStream("temp.xml");
    //org.apache.commons.io.IOUtils.copy(in, temp);
    //temp.close();
    //in.close();
    //in = new FileInputStream("temp.xml");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ie) {
    }
    System.out.println("Parsing!");
    ParseParams params = new ParseParams();
    params.setRegistry(this);
    StructureType st = SdmxIO.parseStructure(params, in);
    if (st == null) {
        System.out.println("St is null!");
    }
    return st;
}

From source file:org.callimachusproject.test.WebResource.java

public WebResource getAppCollection() throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("ACCEPT", "application/atom+xml");
    Assert.assertEquals(con.getResponseMessage(), 203, con.getResponseCode());
    InputStream stream = con.getInputStream();
    String text = new java.util.Scanner(stream).useDelimiter("\\A").next();
    String result = getQuoteAfter("<app:collection", text);
    return ref(result);
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private void handleResponse(HttpURLConnection http, AdaptrisMessage reply)
        throws IOException, InterlokException {
    int responseCode = http.getResponseCode();
    logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    log.trace("Content-Length is " + http.getContentLength());

    if (responseCode < 200 || responseCode > 299) {
        if (ignoreServerResponseCode()) {
            log.trace("Ignoring HTTP Reponse code {}", responseCode);
            responseBody().insert(new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)),
                    reply);/*w w  w  . ja v a  2  s .com*/
        } else {
            fail(responseCode, new InputStreamWithEncoding(http.getErrorStream(), getContentEncoding(http)));
        }
    } else {
        if (getEncoder() != null) {
            AdaptrisMessage decodedReply = getEncoder().readMessage(http);
            AdaptrisMessageImp.copyPayload(decodedReply, reply);
            reply.getObjectHeaders().putAll(decodedReply.getObjectHeaders());
            reply.setMetadata(decodedReply.getMetadata());
        } else {
            responseBody().insert(new InputStreamWithEncoding(http.getInputStream(), getContentEncoding(http)),
                    reply);
        }
    }
    getResponseHeaderHandler().handle(http, reply);
    reply.addMetadata(new MetadataElement(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE,
            String.valueOf(http.getResponseCode())));
    reply.addObjectHeader(CoreConstants.HTTP_PRODUCER_RESPONSE_CODE, Integer.valueOf(http.getResponseCode()));
}