Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.esupportail.nfctagdroid.requestasync.CsnHttpRequestAsync.java

protected String doInBackground(String... params) {

    CsnMessageBean nfcMsg = new CsnMessageBean();
    nfcMsg.setNumeroId(LocalStorage.getValue("numeroId"));
    nfcMsg.setCsn(params[0]);//from ww  w .ja va 2  s. c  o  m
    ObjectMapper mapper = new ObjectMapper();
    String jsonInString = null;
    try {
        jsonInString = mapper.writeValueAsString(nfcMsg);
        URL url = new URL(NfcTacDroidActivity.ESUP_NFC_TAG_SERVER_URL + "/csn-ws");
        log.info("Will call csn-ws on : " + url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.connect();
        Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        writer.write(jsonInString);
        writer.close();
        InputStream inputStream = conn.getInputStream();
        String response = "";
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        while ((line = br.readLine()) != null) {
            response += line;
        }
        conn.disconnect();
        return response;
    } catch (Exception e) {
        throw new NfcTagDroidException(e);
    }
}

From source file:com.inter.trade.view.slideplayview.util.AbFileUtil.java

/**
 * ????.//from   w  w  w .  j  a v  a 2s . co m
 *
 * @param Url 
 * @return int ?
 */
public static int getContentLengthFormUrl(String Url) {
    int mContentLength = 0;
    try {
        URL url = new URL(Url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", Url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent",
                "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            // ????
            mContentLength = mHttpURLConnection.getContentLength();
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (D)
            Log.d(TAG, "?" + e.getMessage());
    }
    return mContentLength;
}

From source file:com.jyzn.wifi.validate.platforminterface.SmsInterfaceImpl.java

@Override
public Map HttpSendSms(String postUrl, String postData) {
    String result = "";
    Map resultMap = Maps.newHashMap();
    try {//from  w  w w.j a  v  a  2  s .  com
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Length", "" + postData.length());

        try {
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();//?
        } catch (IOException e) {
        }

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            resultMap.put("status", "fail");
            //return "fail";
        }

        //??
        String line;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
        }
        resultMap.put("status", "sucess");
        resultMap.put("result", result);
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return resultMap;
}

From source file:com.gmail.ferusgrim.util.UuidGrabber.java

public Map<String, UUID> call() throws Exception {
    JSONParser jsonParser = new JSONParser();
    Map<String, UUID> responseMap = new HashMap<String, UUID>();

    URL url = new URL("https://api.mojang.com/profiles/minecraft");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);//  w ww.j  a  va  2  s .  c o  m
    connection.setDoInput(true);
    connection.setDoOutput(true);

    String body = JSONArray.toJSONString(this.namesToLookup);

    OutputStream stream = connection.getOutputStream();
    stream.write(body.getBytes());
    stream.flush();
    stream.close();

    JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));

    for (Object profile : array) {
        JSONObject jsonProfile = (JSONObject) profile;
        String id = (String) jsonProfile.get("id");
        String name = (String) jsonProfile.get("name");
        UUID uuid = Grab.uuidFromResult(id);
        responseMap.put(name, uuid);
    }

    return responseMap;
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Send form post//from w  ww  .  j av a2  s  .  c  om
 *
 * @param form
 * @param forms
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static Form sendPostForm(Form form, Form[] forms) throws MalformedURLException, IOException {
    URL obj = new URL(form.getUrl().trim());
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setDoInput(true);

    if (forms != null) {
        con.setDoOutput(true);

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

    //add request header
    con.setRequestProperty("User-Agent", DefaultConfig.USER_AGENT);
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Referer", form.getReferer());
    con.setRequestProperty("Origin", form.getOrigin());
    con.setRequestProperty("Host", form.getHost());

    if (COOKIE != null) {
        try {
            con.setRequestProperty("Cookie", COOKIE);
        } catch (Exception ex) {
            DCXLogger.error(Utils.class, Level.SEVERE, ex);
        }
    }

    String urlParameters = "";

    if (forms != null) {
        for (Form fb : forms) {
            urlParameters += "&" + fb.getKey() + "=" + fb.getValue();
        }

        urlParameters = urlParameters.substring(1);

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(urlParameters);
            wr.close();
        }
    }
    if (con.getHeaderField("Set-Cookie") != null) {
        COOKIE = con.getHeaderField("Set-Cookie");
    }

    Form form1 = new Form();
    form1.setResponseCode(con.getResponseCode());
    StringBuilder response = new StringBuilder();

    if (form1.getResponseCode() == 200) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        form1.setResult(response.toString());
    }
    return form1;
}

From source file:ezbake.data.graph.rexster.RexsterRestEzSecurityTokenIntegrationTest.java

/**
 * Tests that the security token has been set by the time the RexsterApplicationGraph is instantiated.
 *
 * @throws java.io.IOException if an error occurred while making the HttpRequest using the URL.
 * @throws org.apache.thrift.TException If an error occurred serializing the token.
 *///from w  w  w .ja  va  2 s.  c o  m
@Test
public void testContextRexster() throws IOException, TException {
    final int rexsterServerPort = properties.getConfiguration().getInteger("http.server-port",
            RexsterSettings.DEFAULT_HTTP_PORT);
    final String rexsterServerHost = properties.getConfiguration().getString("http.server-host", "0.0.0.0");

    final String url = String.format("http://%s:%s/graphs/non-existing-graph", rexsterServerHost,
            rexsterServerPort);

    final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty(HttpHeaders.AUTHORIZATION,
            getAuthorizationHeader(TestUtils.createTS_S_B_User()));

    assertEquals("Not expected result from http request.", "Not Found", connection.getResponseMessage());
}

From source file:gmusic.api.comm.HttpUrlConnector.java

@Override
public String dispatchPost(URI address, String json) throws IOException, URISyntaxException {
    HttpURLConnection connection = prepareConnection(address, true, "POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.connect();//from www  .j  a va 2 s . co m
    connection.getOutputStream().write(json.getBytes());
    if (connection.getResponseCode() != 200) {
        throw new IllegalStateException("Statuscode " + connection.getResponseCode() + " not supported");
    }

    String response = IOUtils.toString(connection.getInputStream());
    if (!isStartup) {
        return response;
    }
    return setupAuthentication(response);
}

From source file:com.vmanolache.mqttpolling.Polling.java

private void sendPost() throws UnsupportedEncodingException, JSONException {
    try {/*from  w  w w. ja  v a  2 s .c o  m*/
        String url = "http://localhost:8080/notifications";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");

        /**
         * POSTing *
         */
        OutputStream os = connection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery()); // should be fine if my getQuery is encoded right yes?
        writer.flush();
        writer.close();
        os.close();
        connection.connect();

        int status = connection.getResponseCode();
        System.out.println(status);
    } catch (IOException ex) {
        Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.thingweb.repository.RepositoryClient.java

/**  This method takes a properties which you are looking for or a SPARQL query  
 * @param search properties or a SPARQL query
 * @return JSON array of relevant TD files (=empty array means no match)
 * *//* w w  w  . j ava 2 s. com*/
public JSONArray tdSearch(String search) throws Exception {

    URL myURL = new URL("http://" + repository_uri + ":" + repository_port + "/td?query=" + search);
    HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
    myURLConnection.setRequestMethod("GET");
    myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    myURLConnection.setDoInput(true);
    myURLConnection.setDoOutput(true);

    InputStream in = myURLConnection.getInputStream();

    JSONArray jsonLDs = new JSONArray(streamToString(in));

    System.out.println(streamToString(in));

    return jsonLDs;
}

From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java

private HttpURLConnection prepHttpConnection(String spec, String method, boolean withPayload)
        throws IOException {
    JiraURL url = baseUrl.withSpec(spec);
    ProxySelector proxySelector = ProxySelector.getDefault();
    HttpURLConnection conn = url.openConnection(proxySelector);
    conn.setRequestProperty("Authorization", "Basic " + auth);
    conn.setRequestProperty("Content-Type", "application/json");

    conn.setRequestMethod(method.toUpperCase());
    if (withPayload) {
        conn.setDoOutput(true);/*from  ww  w .  j a  v a2s .co  m*/
    }
    return conn;
}