Java Code Examples for java.net.HttpURLConnection.setDoOutput()

The following are Jave code examples for showing how to use setDoOutput() of the java.net.HttpURLConnection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: recaptcha-codelab   File: FeedbackServlet.java   Source Code and License Vote up 7 votes
private JSONObject postAndParseJSON(URL url, String postData) throws IOException {
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setDoOutput(true);
  urlConnection.setRequestMethod("POST");
  urlConnection.setRequestProperty(
          "Content-Type", "application/x-www-form-urlencoded");
  urlConnection.setRequestProperty(
          "charset", StandardCharsets.UTF_8.displayName());
  urlConnection.setRequestProperty(
          "Content-Length", Integer.toString(postData.length()));
  urlConnection.setUseCaches(false);
  urlConnection.getOutputStream()
          .write(postData.getBytes(StandardCharsets.UTF_8));
  JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream());
  return new JSONObject(jsonTokener);
}
 
Example 2
Project: chromium-net-for-android   File: CronetFixedModeOutputStreamTest.java   Source Code and License Vote up 7 votes
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testRewind() throws Exception {
    // Post preserving redirect should fail.
    URL url = new URL(NativeTestServer.getRedirectToEchoBody());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length);
    try {
        OutputStream out = connection.getOutputStream();
        out.write(TestUtil.UPLOAD_DATA);
    } catch (HttpRetryException e) {
        assertEquals("Cannot retry streamed Http body", e.getMessage());
    }
    connection.disconnect();
}
 
Example 3
Project: ProyectoPacientes   File: DigestAuthentication.java   Source Code and License Vote up 6 votes
/**
 * Get the digest challenge header by connecting to the resource
 * with no credentials.
 */
public static String getChallengeHeader(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.getOutputStream().close();
    try {
        conn.getInputStream().close();
    } catch (IOException ex) {
        if (401 == conn.getResponseCode()) {
            // we expect a 401-unauthorized response with the
            // WWW-Authenticate header to create the request with the
            // necessary auth data
            String hdr = conn.getHeaderField("WWW-Authenticate");
            if (hdr != null && !"".equals(hdr)) {
                return hdr;
            }
        } else if (400 == conn.getResponseCode()) {
            // 400 usually means that auth is disabled on the Fabric node
            throw new IOException("Fabric returns status 400. If authentication is disabled on the Fabric node, "
                    + "omit the `fabricUsername' and `fabricPassword' properties from your connection.");
        } else {
            throw ex;
        }
    }
    return null;
}
 
Example 4
Project: dropwizard-prometheus   File: Pushgateway.java   Source Code and License Vote up 6 votes
@Override
public void connect() throws IllegalStateException, IOException {
    if (isConnected()) {
        throw new IllegalStateException("Already connected");
    }

    String url = "http://" + hostname + ":" + port + "/metrics/job/" + URLEncoder.encode(job, "UTF-8");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("Content-Type", TextFormat.REQUEST_CONTENT_TYPE);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");

    conn.setConnectTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.setReadTimeout(10 * SECONDS_PER_MILLISECOND);
    conn.connect();

    this.connection = conn;
    this.writer = new PrometheusTextWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)));
    this.exporter = new DropwizardMetricsExporter(writer);
}
 
Example 5
Project: NEILREN4J   File: PhilisenseKaoQinService.java   Source Code and License Vote up 6 votes
/**
 * 登陆获取 Cookie
 *
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private String postLogin(String username, String password) throws Exception {
    String meCookie = null;//(String) memcachedManager.get("PLX_" + username + "_" + password);
    if (meCookie != null && !meCookie.equals("")) {
        this.Cookie = meCookie;
        return meCookie;
    }
    URL url = new URL(PLX + "/WebRoot/LoginAction.do");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setUseCaches(false);

    con.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded; text/html; charset=UTF-8");
    con.setConnectTimeout(1000);
    con.setReadTimeout(3000);
    OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
    osw.write("activity=login&userId=" + username + "&password=" + password);
    osw.flush();
    osw.close();
    /////////////
    //从请求中获取cookie列表
    String cookieskey = "Set-Cookie";
    Map<String, List<String>> maps = con.getHeaderFields();
    List<String> coolist = maps.get(cookieskey);
    Iterator<String> it = coolist.iterator();
    StringBuffer sbu = new StringBuffer();
    while (it.hasNext()) {
        sbu.append(it.next() + ";");
    }
    String cookies = sbu.toString();
    cookies = cookies.substring(0, cookies.length() - 1);
    this.Cookie = cookies;
    //memcachedManager.set("PLX_" + username + "_" + password, cookies, 300);
    return cookies;
}
 
Example 6
Project: chromium-net-for-android   File: CronetChunkedOutputStreamTest.java   Source Code and License Vote up 6 votes
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testGetOutputStreamAfterConnectionMade() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setChunkedStreamingMode(0);
    assertEquals(200, connection.getResponseCode());
    try {
        connection.getOutputStream();
        fail();
    } catch (ProtocolException e) {
        // Expected.
    }
}
 
Example 7
Project: javaide   File: GitHubClient.java   Source Code and License Vote up 6 votes
/**
 * Send parameters to output stream of request
 *
 * @param request
 * @param params
 * @throws IOException
 */
protected void sendParams(HttpURLConnection request, Object params)
        throws IOException {
    request.setDoOutput(true);
    if (params != null) {
        request.setRequestProperty(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON
                + "; charset=" + CHARSET_UTF8); //$NON-NLS-1$
        byte[] data = toJson(params).getBytes(CHARSET_UTF8);
        request.setFixedLengthStreamingMode(data.length);
        BufferedOutputStream output = new BufferedOutputStream(
                request.getOutputStream(), bufferSize);
        try {
            output.write(data);
            output.flush();
        } finally {
            try {
                output.close();
            } catch (IOException ignored) {
                // Ignored
            }
        }
    } else {
        request.setFixedLengthStreamingMode(0);
        request.setRequestProperty("Content-Length", "0");
    }
}
 
Example 8
Project: trvlr-backend   File: ApiService.java   Source Code and License Vote up 6 votes
protected JSONObject post(URL url, String json_body) throws IOException {

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");

		OutputStream os = conn.getOutputStream();
		os.write(json_body.getBytes("UTF-8"));
		os.close();

		// read the response
		InputStream in = new BufferedInputStream(conn.getInputStream());
		String result = IOUtils.toString(in, "UTF-8");
		JSONObject jsonObject = new JSONObject(result);

		in.close();
		conn.disconnect();

		return jsonObject;
	}
 
Example 9
Project: CaptivePortalAutologin   File: CaptivePortalLoginActivity.java   Source Code and License Vote up 6 votes
private void doPostRequest(String destination, String parms) throws IOException {
    URL url = new URL(destination);
    String response = "";
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(parms);
    writer.flush();
    writer.close();
    os.close();

    conn.connect();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        String line;
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line=br.readLine()) != null) {
            response+=line;
        }
    }
    else {
        response="";

    }
}
 
Example 10
Project: iosched-reader   File: BasicRequestHandler.java   Source Code and License Vote up 5 votes
@Override
public void prepareConnection(HttpURLConnection urlConnection, HttpMethod httpMethod,
        String contentType) throws IOException {
    // Configure connection for request method
    urlConnection.setRequestMethod(httpMethod.getMethodName());
    urlConnection.setDoOutput(httpMethod.getDoOutput());
    urlConnection.setDoInput(httpMethod.getDoInput());
    if (contentType != null) {
        urlConnection.setRequestProperty("Content-Type", contentType);
    }
    // Set additional properties
    urlConnection.setRequestProperty("Accept-Charset", UTF8);
}
 
Example 11
Project: cos-java-sdk-v5   File: GeneratePresignedUrlTest.java   Source Code and License Vote up 5 votes
@Test
public void testPutFile() throws IOException {
    if (!judgeUserInfoValid()) {
        return;
    }
    String key = "ut/generate_url_test_upload.txt";
    File localFile = buildTestFile(1024);
    Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
    URL url = cosclient.generatePresignedUrl(bucket, key, expirationTime, HttpMethodName.PUT);

    System.out.println(url.toString());

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

    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(localFile));
    int readByte = -1;
    while ((readByte = bis.read()) != -1) {
        bos.write(readByte);
    }
    bis.close();
    bos.close();
    int responseCode = connection.getResponseCode();
    assertEquals(200, responseCode);

    headSimpleObject(key, localFile.length(), Md5Utils.md5Hex(localFile));
    clearObject(key);
    localFile.delete();
}
 
Example 12
Project: PlusGram   File: HurlStack.java   Source Code and License Vote up 5 votes
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}
 
Example 13
Project: GitHub   File: ResponseCacheTest.java   Source Code and License Vote up 5 votes
private void addRequestBodyIfNecessary(String requestMethod, HttpURLConnection connection)
    throws IOException {
  if (requestMethod.equals("POST") || requestMethod.equals("PUT")) {
    connection.setDoOutput(true);
    OutputStream requestBody = connection.getOutputStream();
    requestBody.write('x');
    requestBody.close();
  }
}
 
Example 14
Project: GitHub   File: UrlConnectionCacheTest.java   Source Code and License Vote up 5 votes
private void addRequestBodyIfNecessary(String requestMethod, HttpURLConnection invalidate)
    throws IOException {
  if (requestMethod.equals("POST") || requestMethod.equals("PUT")) {
    invalidate.setDoOutput(true);
    OutputStream requestBody = invalidate.getOutputStream();
    requestBody.write('x');
    requestBody.close();
  }
}
 
Example 15
Project: APacheSynapseSimplePOC   File: JSF.java   Source Code and License Vote up 5 votes
public static void main ( String[] args ) {

        if ( args.length < 3 ) {
            System.err.println(JSF.class.getName() + " <view_url> <payload_type> <payload_arg>");
            System.exit(-1);
        }

        final Object payloadObject = Utils.makePayloadObject(args[ 1 ], args[ 2 ]);

        try {
            URL u = new URL(args[ 0 ]);

            URLConnection c = u.openConnection();
            if ( ! ( c instanceof HttpURLConnection ) ) {
                throw new IllegalArgumentException("Not a HTTP url");
            }

            HttpURLConnection hc = (HttpURLConnection) c;
            hc.setDoOutput(true);
            hc.setRequestMethod("POST");
            hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream os = hc.getOutputStream();

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(payloadObject);
            oos.close();
            byte[] data = bos.toByteArray();
            String requestBody = "javax.faces.ViewState=" + URLEncoder.encode(Base64.encodeBase64String(data), "US-ASCII");
            os.write(requestBody.getBytes("US-ASCII"));
            os.close();

            System.err.println("Have response code " + hc.getResponseCode() + " " + hc.getResponseMessage());
        }
        catch ( Exception e ) {
            e.printStackTrace(System.err);
        }
        Utils.releasePayload(args[1], payloadObject);

    }
 
Example 16
Project: SparseBukkitAPI   File: SpigotResourceVersionChecker.java   Source Code and License Vote up 5 votes
public String getVersion(int resource) throws IOException
{
	HttpURLConnection con = (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection();
	con.setDoOutput(true);
	con.setRequestMethod("POST");
	con.getOutputStream().write(("key=" + API_KEY + "&resource=" + resource).getBytes("UTF-8"));
	return new BufferedReader(new InputStreamReader(con.getInputStream())).readLine();
}
 
Example 17
Project: OrthancAnonymization   File: QueryAnon.java   Source Code and License Vote up 4 votes
public void sendQuery(String level, String id) throws IOException{
	this.setQuery();
	this.setUrl(level + "/" + id +"/anonymize");
	URL url = new URL(this.url);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setDoOutput(true);
	if((fullAddress != null && fullAddress.contains("https")) || (ip != null && ip.contains("https"))){
		try{
			HttpsTrustModifier.Trust(conn);
		}catch (Exception e){
			throw new IOException("Cannot allow self-signed certificates");
		}
	}
	if(this.authentication != null){
		conn.setRequestProperty("Authorization", "Basic " + this.authentication);
	}
	OutputStream os = conn.getOutputStream();
	os.write(this.query.getBytes());
	os.flush();
	if (conn.getResponseCode() != 200) {
		throw new RuntimeException("Failed : HTTP error code : "
				+ conn.getResponseCode());
	}
	conn.getResponseMessage();
	BufferedReader br = new BufferedReader(new InputStreamReader(
			(conn.getInputStream())));

	// We get the study ID at the end
	StringBuilder sb = new StringBuilder();
	String output;
	while ((output = br.readLine()) != null) {
		sb.append(output);
	}
	String pattern1 = "\"ID\" : \"";
	String pattern2 = "\",";
	Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
	Matcher m = p.matcher(sb.toString());
	while(m.find()){
		this.newUID = m.group(1);
	}
	pattern1 = "\"PatientID\" : \"";
	pattern2 = "\",";
	p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
	m = p.matcher(sb.toString());
	while(m.find()){
		this.newPatientUID = m.group(1);
	}
	conn.disconnect();
}
 
Example 18
Project: ServerlessPlatform   File: ClimateService.java   Source Code and License Vote up 4 votes
private String fetchWeather(String myURL) {
    String toret = null;
    String file_content = readFile();
    System.out.println("File contents: "+file_content);
    HashMap<String, String> hmap = parse(file_content);
    
    // check if for current URL already request has been made and result is still valid        
    if(hmap.containsKey(myURL) && Long.parseLong(hmap.get(myURL).split("\\|")[0]) + 7200000 >= Long.parseLong(getTimestamp())){
    	System.out.println("Sending from the file");
    	return hmap.get(myURL).split("\\|")[1];
    }
    
	else {
		System.out.println("Connecting the Web API");
     try {
         String uurl = myURL;
         /*String proxy = "proxy.iiit.ac.in", port = "8080";
         Properties systemProperties = System.getProperties();
         systemProperties.setProperty("http.proxyHost",proxy);
         systemProperties.setProperty("http.proxyPort",port);*/
         URL url = new URL (uurl);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("GET");
         connection.setDoOutput(true);
         InputStream content = (InputStream)connection.getInputStream();
         BufferedReader in   = new BufferedReader (new InputStreamReader (content));
         String line;
         toret = in.readLine();
         while ((line = in.readLine()) != null) {
             toret += line;
         }
         
      // update currentWeather file	        	
      hmap.put(myURL, getTimestamp()+"|"+toret);
      FileWriter f = new FileWriter(currentWeather);
      //write on file
      for (String key : hmap.keySet()) {
         f.write(key+"|"+hmap.get(key)+"\n");
      }
      f.close();
     } catch(Exception e) {
         e.printStackTrace();
     }

	}
    return toret;
}
 
Example 19
Project: SubtitleDownloader   File: HTTPRequest.java   Source Code and License Vote up 4 votes
private String sendPostSubtitleSUBDB(String videoHash, String subtitlePath) throws Exception {
    String url = URL + "?action=upload&hash=" + videoHash;
    String boundary = "xYzZY";
    String LINE_FEED = "\r\n";
    File subtitleFile = new File(subtitlePath);
    long dataLength = subtitleFile.length();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT_SUBDB);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    con.setRequestProperty("Content-Length", Long.toString(dataLength));
    // Send post request
    con.setDoOutput(true);
    try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {

        StringBuilder temp = new StringBuilder();
        wr.writeBytes("--" + boundary + LINE_FEED);
        temp.append("--").append(boundary).append(LINE_FEED);
        wr.writeBytes("Content-Disposition: form-data; name=" + "\"hash\"" + LINE_FEED);
        wr.writeBytes(LINE_FEED);
        temp.append("Content-Disposition: form-data; name=\"hash\"").append(LINE_FEED);
        temp.append(LINE_FEED);
        wr.writeBytes(videoHash + LINE_FEED);
        temp.append(videoHash).append(LINE_FEED);
        wr.writeBytes("--" + boundary + LINE_FEED);
        temp.append("--").append(boundary).append(LINE_FEED);
        wr.writeBytes("Content-Disposition: form-data; name=" + "\"file\"; " + "filename=" + "\"subtitle.srt\"" + LINE_FEED);
        temp.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(videoHash).append(".srt\"").append(LINE_FEED);
        wr.writeBytes("Content-Type: application/octet-stream");
        temp.append("Content-Type: application/octet-stream");
        wr.writeBytes(LINE_FEED);
        wr.flush();
        temp.append(LINE_FEED);
        wr.write(Files.readAllBytes(Paths.get(subtitlePath)));
        wr.writeBytes(LINE_FEED);
        temp.append(Arrays.toString(Files.readAllBytes(Paths.get(subtitlePath)))).append("\n len=").append(Files.readAllBytes(Paths.get(subtitlePath)).length);
        //temp.append(LINE_FEED);
        //wr.writeBytes("--"+boundary+LINE_FEED);
        //temp.append("--").append(boundary).append(LINE_FEED);
        wr.flush();
        System.out.println("check: \n" + temp.toString());
    }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + url);
    System.out.println("Response Code : " + responseCode);
    System.out.println("dataLength: " + Long.toString(dataLength));

    StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }
    //print result
    System.out.println(response.toString());
    return response.toString();
}
 
Example 20
Project: RFID-Attendance   File: SendToServer.java   Source Code and License Vote up 4 votes
private void sendJSon(String output, String urlOut) throws Exception {

            try {
                URL url = new URL(urlOut);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setReadTimeout(10000); // 10 seconds
                connection.setConnectTimeout(15000); // 15 seconds
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                connection.setRequestProperty("Accept", "application/json");
                connection.setDoOutput(true); // You need to set it to true  if you want to send (output) a request body
                connection.connect();

                OutputStream outputStream = connection.getOutputStream();
                DataOutputStream dStream = new DataOutputStream(outputStream);
                dStream.writeBytes(output); // Writes out the string to the underlying output stream as a sequence of bytes
                dStream.flush(); // Flushes the data output stream.
                dStream.close(); // Closing the output stream.
                Log.d(LOG_TAG, urlOut + " Sent String " + output);

                //====== response from server
                int responseCode = connection.getResponseCode();
                if(responseCode > 199 && responseCode < 208) {
                    Log.d(urlOut + " Response ", responseCode + "");
                } else {
                    Log.d(urlOut + " Response Code bad", responseCode + "");

                    // User is already registered
                    if(responseCode == 400) {
                        SaveData.remove();

                        if(context != null)
                            showErrorToast(context.getString(R.string.error_already_registered));
                        Log.d(urlOut + " not added to queue", "is reg Duplicate" + urlOut);
                    }
                    else {
                        showErrorToast("Error: " + responseCode);
                    }

                    throw new Exception();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(urlOut + " Error ", output + " exception: " + e);
                throw new Exception();
            }
        }