Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:com.example.austin.test.TextActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text);

    Thread thread = new Thread(new Runnable() {
        @Override//from w w  w. j a v  a2 s  .co  m
        public void run() {
            try {
                Bundle bundle = getIntent().getExtras();
                Bitmap photo = (Bitmap) bundle.get("photo");
                ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 100, stream1);
                byte[] fileContent = stream1.toByteArray();

                String license_code = "59D1D7B4-61FD-49EB-A549-C77E08B7103A";
                String user_name = "austincheng16";

                String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";
                URL url = new URL(ocrURL);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Authorization", "Basic "
                        + new String(Base64.encodeBase64((user_name + ":" + license_code).getBytes())));

                connection.setRequestProperty("Content-Type", "application/json");

                connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

                try {
                    OutputStream stream = connection.getOutputStream();

                    stream.write(fileContent);
                    stream.close();

                    int httpCode = connection.getResponseCode();

                    if (httpCode == HttpURLConnection.HTTP_OK) {
                        String jsonResponse = GetResponseToString(connection.getInputStream());
                        PrintOCRResponse(jsonResponse);
                    } else {
                        String jsonResponse = GetResponseToString(connection.getErrorStream());
                        JSONParser parser = new JSONParser();
                        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);
                        Log.i("austin", "Error Message: " + jsonObj.get("ErrorMessage"));
                    }
                    connection.disconnect();
                } catch (IOException e) {
                    Log.i("austin", "IOException");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    thread.start();
}

From source file:org.openxdata.server.servlet.DataImportServletTest.java

@Test
@Ignore("this is an integration test for localhost")
public void integrationTest() throws Exception {
    final String urlString = "http://localhost:8888/org.openxdata.server.admin.OpenXDataServerAdmin/dataimport?msisdn=2222222";
    final String userName = "dagmar";
    final String password = "dagmar";

    // open url connection
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setDoOutput(true);//  w  ww . j av  a 2s. co  m
    con.setDoInput(true);
    con.setChunkedStreamingMode(1024);

    // stuff the Authorization request header
    byte[] encodedPassword = (userName + ":" + password).getBytes();
    con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(encodedPassword)));

    // put the form data on the output stream
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeByte(new Integer(1));
    String data = "<?xml version='1.0' encoding='UTF-8' ?><cmt_lesotho_tlpp_session_report_v1 formKey=\"cmt_lesotho_tlpp_session_report_v1\" id=\"2\" name=\"Treatment literacy programme_v1\" xmlns:xf=\"http://www.w3.org/2002/xforms\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">  <name>TEEHEE</name>  <session_type>treatment_literacy_session</session_type>  <session_date>2010-04-15</session_date>  <district>berea</district>  <session_location>secondary_school</session_location>  <session_location_other/>  <session_place_name>dsds</session_place_name>  <participant_number_male>1</participant_number_male>  <participant_number_female>2</participant_number_female>  <session_start_time>10:22:00</session_start_time>  <session_finish_time>01:22:00</session_finish_time>  <session_topic>children_HIV_incl_ARVs</session_topic>  <session_topic_other/>  <support_group>false</support_group>  <one_on_one_session>false</one_on_one_session>  <CMT_AV_kit>false</CMT_AV_kit>  <CMT_DVD>false</CMT_DVD>  <CMT_co_facilitator>false</CMT_co_facilitator>  <co_facilitator_name/>  <clinic_hospital_department/>  <clinic_hospital_department_other/>  <clinic_hospital_TV/>  <school_grade>12</school_grade>  <school_CMT_materials>true</school_CMT_materials>  <session_confirmed>true</session_confirmed></cmt_lesotho_tlpp_session_report_v1>";
    out.writeUTF(data);
    out.flush();

    // pull the information back from the URL
    InputStream is = con.getInputStream();
    StringBuffer buf = new StringBuffer();
    int c;
    while ((c = is.read()) != -1) {
        buf.append((char) c);
    }
    con.disconnect();

    // output the information
    System.out.println(buf);
}

From source file:org.compose.mobilesdk.android.ServerRequestTask.java

public String doPUTRequest(URL requestUrl) {
    String responseString = null;

    try {/*from  w  w  w.j a  v  a  2s  .  c  o m*/
        HttpURLConnection httpCon = (HttpURLConnection) requestUrl.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Authorization", header_parameters);
        httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        httpCon.setRequestProperty("Accept", "*/*");

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("" + this.message);
        out.close();

        if (DEBUG) {
            BufferedReader in = null;
            if (httpCon.getErrorStream() != null)
                in = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
            else
                in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {

                Log.i(DEBUG_INFO, inputLine);
            }
            in.close();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return responseString;
}

From source file:org.bitrepository.protocol.http.HttpFileExchange.java

/**
 * Retrieves the Input stream for a given URL.
 * @param url The URL to retrieve./*from   w  w  w.j  a v a 2 s .com*/
 * @return The InputStream to the given URL.
 * @throws IOException If any problems occurs during the retrieval.
 */
protected InputStream retrieveStream(URL url) throws IOException {
    HttpURLConnection conn = getConnection(url);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    return conn.getInputStream();
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromHttpToFile(String theURL, String theParameters, String theFile) throws IOException {
    // both in milliseconds
    //int connectionTimeout = 1000 * 60 * 3;
    //int readTimeout = 1000 * 60 * 3;
    try {/*from   w ww  .j  a v  a  2  s .c  om*/
        URL myURL = new URL(theURL);
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        //connection.setRequestProperty("charset", "utf-8");
        if (null != theParameters) {
            System.out.println("Content-Length " + Integer.toString(theParameters.getBytes().length));
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(theParameters.getBytes().length));
        }
        connection.setUseCaches(false);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            if (null != theParameters) {
                wr.write(theParameters.getBytes());
            }
            wr.flush();
            File myFile = new File(theFile);
            System.out.println("Requesting " + myURL);
            FileUtils.copyInputStreamToFile(connection.getInputStream(), myFile);
            System.out.println("Downloaded " + myURL);
        } catch (IOException rethrownExp) {
            InputStream errorStr = connection.getErrorStream();
            if (null != errorStr) {
                System.err.println("Error stream returned: " + IOUtils.toString(errorStr));
            } else {
                System.err.println("No error stream returned");
            }
            throw rethrownExp;
        }
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage() + " thrown while downloading " + theURL
                + " to " + theFile);
        throw rethrownExp;
    }
}

From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java

@Override
public void run() {
    debug("THREAD STARTED");
    long start = getNow();
    while (start + TIMEOUT <= getNow() && player == null) {
    }//from  www .j  a  v a2 s .  co  m
    this.stopThread();
    this.deregister();
    if (player == null)
        return;

    boolean alreadyActivated = false;
    boolean isActivated = false;

    try {
        String x = player.getSavedVariable("xenforo");
        alreadyActivated = x.equalsIgnoreCase("yes");
    } catch (Exception e) {
    }

    try {
        String url = XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", "") + APPEND;
        if (url.equals(APPEND))
            return;

        String encodedData = "name=" + encode("username") + "&value=" + encode(this.player.getPlayer())
                + "&_xfResponseType=json";
        //String rawData = "name=username";
        String type = "application/x-www-form-urlencoded; charset=UTF-8";
        //String encodedData = URLEncoder.encode(rawData, "ISO-8859-1"); 
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", type);
        conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Referer", XenforoManager.XENFORO_MANAGER.yml.getString("xenforo.root", ""));
        conn.setUseCaches(false);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(encodedData);
        wr.flush();

        InputStream in = conn.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();

        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);

        String out = responseStrBuilder.toString();
        JSONObject o = (JSONObject) JSONValue.parse(out);
        try {
            isActivated = o.get("_redirectMessage").toString().equalsIgnoreCase("ok");
        } catch (NullPointerException e) {
            isActivated = true;
        }
        debug("GOT: " + isActivated);
    } catch (Exception e) {
        if (DebugMode)
            e.printStackTrace();
        return;
    }

    player.setSavedVariable("xenforo", (isActivated ? "yes" : "no"));
    player.save();

    if (isActivated && !alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onRegistered"));
    }

    if (!isActivated && alreadyActivated) {
        runCommands(XenforoManager.XENFORO_MANAGER.yml.getStringList("commands.onDeRegistered"));
    }
}

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 ww. j a v a 2  s .c  o  m
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.mp3tunes.android.player.RemoteAlbumArtHandler.java

private Bitmap getArtwork(Track t) {
    String urlstr = null;//from www  .j a  v  a  2  s . c  o  m
    InputStream is = null;
    String file = getArtFile(t);

    if (file != null) {
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        try {
            urlstr = getArtUrl(t);
            URL url = new URL(urlstr);

            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setDoInput(true);
            c.connect();
            is = c.getInputStream();
        } catch (MalformedURLException e) {
            Log.d("RemoteImageHandler", "RemoteImageWorker passed invalid URL: " + urlstr);
        } catch (IOException e) {
        }

    }
    if (is == null)
        return null;
    Bitmap img;
    img = BitmapFactory.decodeStream(is);
    return img;
}

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);//from   www  .  j  a  v  a  2  s  .  com
    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:cloudlens.engine.CL.java

public Object post(String urlString, String jsonData) throws IOException {
    final URL url = new URL(urlString);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from  w  w  w  .  j a  v a  2  s.  com*/
    conn.setDoInput(true);
    final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString);
    if (matcher.find()) {
        final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encoding);
    }
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestMethod("POST");

    try (final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
        wr.write(jsonData);
        wr.flush();
    }
    try (final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        String line;
        final StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        final String s = StringEscapeUtils.escapeEcmaScript(sb.toString());
        final Object log = engine.eval(
                "CL.log=JSON.parse(\"" + s + "\").hits.hits.map(function (entry) { return entry._source})");
        return log;
    }
}