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

The following are Jave code examples for showing how to use setRequestMethod() 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.
+ Save this method
Example 1
Project: chromium-net-for-android   File: CronetFixedModeOutputStreamTest.java   View Source Code Vote up 7 votes
@SmallTest
@Feature({"Cronet"})
@CompareDefaultWithCronet
public void testWriteLessThanContentLength()
        throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    // Set a content length that's 1 byte more.
    connection.setFixedLengthStreamingMode(TestUtil.UPLOAD_DATA.length + 1);
    OutputStream out = connection.getOutputStream();
    out.write(TestUtil.UPLOAD_DATA);
    try {
        connection.getResponseCode();
        fail();
    } catch (ProtocolException e) {
        // Expected.
    }
    connection.disconnect();
}
 
Example 2
Project: Transwarp-Sample-Code   File: KerberosWebHDFSConnection2.java   View Source Code Vote up 6 votes
/**
 * <b>RENAME</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=RENAME
 * &destination=<PATH>[&createParent=<true|false>]"
 *
 * @param srcPath
 * @param destPath
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String rename(String srcPath, String destPath)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();

    HttpURLConnection conn = authenticatedURL.openConnection(
            new URL(new URL(httpfsUrl), MessageFormat.format(
                    "/webhdfs/v1/{0}?op=RENAME&destination={1}",
                    URLUtil.encodePath(srcPath),
                    URLUtil.encodePath(destPath))), token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 3
Project: Transwarp-Sample-Code   File: PseudoWebHDFSConnection.java   View Source Code Vote up 6 votes
/**
 * <b>CREATESYMLINK</b>
 *
 * curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=CREATESYMLINK
 * &destination=<PATH>[&createParent=<true|false>]"
 *
 * @param srcPath
 * @param destPath
 * @return
 * @throws AuthenticationException
 * @throws IOException
 * @throws MalformedURLException
 */
public String createSymLink(String srcPath, String destPath)
        throws MalformedURLException, IOException, AuthenticationException {
    String resp = null;
    ensureValidToken();
    String spec = MessageFormat
            .format("/webhdfs/v1/{0}?op=CREATESYMLINK&destination={1}&user.name={2}",
                    URLUtil.encodePath(srcPath),
                    URLUtil.encodePath(destPath), this.principal);
    HttpURLConnection conn = authenticatedURL.openConnection(new URL(
            new URL(httpfsUrl), spec), token);
    conn.setRequestMethod("PUT");
    conn.connect();
    resp = result(conn, true);
    conn.disconnect();

    return resp;
}
 
Example 4
Project: KMUC   File: Carte.java   View Source Code Vote up 6 votes
/**
 * 네트워크 연결을 통한 모든 메뉴 JSON 파싱
 * @param reqAddress 모든 파라미터가 포함된 리퀘스트 주소
 * @return 모든 메뉴가 담긴 JSONObject
 * @throws IOException
 * @throws ParseException
 */
private JSONObject getAllMenuJson(String reqAddress) throws IOException, ParseException {
	HttpURLConnection conn = (HttpURLConnection)new URL(reqAddress).openConnection();
	conn.setRequestMethod("GET");
	conn.setRequestProperty("User-Agent", "Mozilla/5.0");
	conn.setConnectTimeout(5000);
	
	BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	String line;
	StringBuilder sb = new StringBuilder();
	
	while((line = br.readLine()) != null){
		sb.append(line);
	}
	br.close();
	
	
	JSONParser parser = new JSONParser();
	JSONObject allMenu = (JSONObject)parser.parse(replace(sb.toString()));

	return allMenu;
}
 
Example 5
Project: chromium-net-for-android   File: CronetBufferedOutputStreamTest.java   View Source Code Vote up 6 votes
/**
 * Tests write after connect. Strangely, the default implementation allows
 * writing after being connected, so this test only runs against Cronet's
 * implementation.
 */
@SmallTest
@Feature({"Cronet"})
@OnlyRunCronetHttpURLConnection
public void testWriteAfterConnect() throws Exception {
    URL url = new URL(NativeTestServer.getEchoBodyURL());
    HttpURLConnection connection =
            (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    OutputStream out = connection.getOutputStream();
    out.write(TestUtil.UPLOAD_DATA);
    connection.connect();
    try {
        // Attemp to write some more.
        out.write(TestUtil.UPLOAD_DATA);
        fail();
    } catch (IllegalStateException e) {
        assertEquals("Cannot write after being connected.", e.getMessage());
    }
}
 
Example 6
Project: jdk8u-jdk   File: FixedLengthInputStream.java   View Source Code Vote up 5 votes
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 7
Project: decoy   File: HttpClientWrapper.java   View Source Code Vote up 5 votes
private static <T> HttpURLConnection buildPost(String urlStr, final Map<String, String> headers, T body) throws IOException {
    URL url = new URL(urlStr);

    // conn
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    configUrlConnection(urlConnection);
    urlConnection.setRequestMethod(HTTP_POST);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);

    // headers
    buildHeaders(urlConnection, headers);

    // body
    OutputStream os = urlConnection.getOutputStream();
    DataOutputStream out = new DataOutputStream(os);
    IOException exception = null;
    try {
        if (body instanceof String) {
            out.write(((String) body).getBytes(CHARSET));
        } else if (body instanceof byte[]) {
            out.write((byte[]) body);
        }
        os.flush(); // 开始与对方建立三次握手。
    } catch (IOException e) {
        exception = e;
    } finally {
        out.close();
        os.close();
    }

    if (exception != null) {
        throw exception;
    }

    return urlConnection;
}
 
Example 8
Project: AssistantBySDK   File: DownloadTask.java   View Source Code Vote up 5 votes
private void download() throws Exception {
    int startpos = threaid * block + beginLenght;//计算该线程从文件的什么位置开始下载
    int endpos = (threaid + 1) * block - 1;//计算该线程下载到文件的什么位置结束
    System.out.println("threaid=" + threaid + ",startpos=" + startpos + ",endpos=" + endpos + ", url = " + url);
    endpos = endpos >= fileSize ? fileSize - 1 : endpos;
    System.out.println("threaid=" + threaid + ",startpos=" + startpos + ",endpos=" + endpos);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(10 * 1000);
    conn.setRequestMethod("GET");
    conn.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, */*");
    conn.setRequestProperty("Accept-Language", "zh-CN");
    conn.setRequestProperty("Charset", "UTF-8");
    conn.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)");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Range", "bytes=" + startpos + "-" + endpos);
    InputStream inputStream = conn.getInputStream();

    System.out.println("threaid=" + threaid + ",startpos=" + startpos + ",endpos=" + endpos + ",contentLength=" + conn.getContentLength());
    RandomAccessFile rfile = new RandomAccessFile(file, "rwd");
    rfile.seek(startpos);
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        rfile.write(buffer, 0, len);
        beginLenght += len;
        update(threaid, beginLenght);
        append(len);
        if (pause) {
            System.out.println("break " + threaid);
            break;
        }
    }
    rfile.close();
    inputStream.close();
    conn.disconnect();
}
 
Example 9
Project: url-to-google-drive   File: ResumableDriveUploader.java   View Source Code Vote up 5 votes
private byte[] downloadPartially(long start, long end) {
	try {
		HttpURLConnection downloadConnection = (HttpURLConnection) downloadFileInfo.getUploadUrl().openConnection();

		downloadConnection.setRequestMethod("GET");
		String rangeHeaderValue = "bytes=" + start + "-" + end;
		downloadConnection.setRequestProperty("Range", rangeHeaderValue);
		downloadConnection.setRequestProperty("User-Agent", USER_AGENT);
		InputStream in = downloadConnection.getInputStream();
		return IOUtils.toByteArray(in);
	} catch (Exception e) {
		throw new RuntimeException("Can not download file", e);
	}
}
 
Example 10
Project: AndroidSourceViewer   File: HttpUtil.java   View Source Code Vote up 5 votes
/**
 * Get 请求
 *
 * @param uri
 * @return
 * @throws Exception
 */
public static String syncGet(String uri) throws Exception {
    URL url = new URL(uri);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5 * 1000);
    conn.setRequestMethod("GET");
    InputStream inStream = conn.getInputStream();
    String result = new String(StreamUtil.loadFromStream(inStream));
    return result;
}
 
Example 11
Project: openjdk-jdk10   File: StreamingRetry.java   View Source Code Vote up 5 votes
void test(String method) throws Exception {
    ss = new ServerSocket(0);
    ss.setSoTimeout(ACCEPT_TIMEOUT);
    int port = ss.getLocalPort();

    Thread otherThread = new Thread(this);
    otherThread.start();

    try {
        URL url = new URL("http://localhost:" + port + "/");
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoOutput(true);
        if (method != null)
            uc.setRequestMethod(method);
        uc.setChunkedStreamingMode(4096);
        OutputStream os = uc.getOutputStream();
        os.write("Hello there".getBytes());

        InputStream is = uc.getInputStream();
        is.close();
    } catch (IOException expected) {
        //expected.printStackTrace();
    } finally {
        ss.close();
        otherThread.join();
    }
}
 
Example 12
Project: EchoPet   File: UUIDFetcher.java   View Source Code Vote up 5 votes
private static HttpURLConnection createConnection() throws Exception {
    URL url = new URL(PROFILE_URL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    return connection;
}
 
Example 13
Project: APacheSynapseSimplePOC   File: JSF.java   View Source Code 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 14
Project: GitHub   File: URLConnectionTest.java   View Source Code Vote up 5 votes
@Test public void streamedBodyIsRetriedOnHttp2Shutdown() throws Exception {
  enableProtocol(Protocol.HTTP_2);
  server.enqueue(new MockResponse()
      .setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)
      .setBody("abc"));
  server.enqueue(new MockResponse()
      .setBody("def"));

  HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
  connection1.setChunkedStreamingMode(4096);
  connection1.setRequestMethod("POST");
  connection1.connect(); // Establish healthy HTTP/2 connection, but don't write yet.

  // Send a separate request which will trigger a GOAWAY frame on the healthy connection.
  HttpURLConnection connection2 = urlFactory.open(server.url("/").url());
  assertContent("abc", connection2);

  // Ensure the GOAWAY frame has time to be read and processed.
  Thread.sleep(500);

  OutputStream os = connection1.getOutputStream();
  os.write(new byte[] { '1', '2', '3' });
  os.close();
  assertContent("def", connection1);

  RecordedRequest request1 = server.takeRequest();
  assertEquals(0, request1.getSequenceNumber());

  RecordedRequest request2 = server.takeRequest();
  assertEquals("123", request2.getBody().readUtf8());
  assertEquals(0, request2.getSequenceNumber());
}
 
Example 15
Project: bubichain-sdk-java   File: HttpKit.java   View Source Code Vote up 5 votes
/**
 *  鍙戦�丳ost璇锋眰
 * @param url 璇锋眰鍦板潃
 * @param params 璇锋眰鍙傛暟
 * @param https 鏄惁鍚姩https
 * @return
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	if(enableSSL){
		return post(url,params,true);
	}else{
		StringBuffer bufferRes = null;
     URL urlGet = new URL(url);
     HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
     // 杩炴帴瓒呮椂
     http.setConnectTimeout(50000);
     // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
     http.setReadTimeout(50000);
     http.setRequestMethod("POST");
     http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
     http.setDoOutput(true);
     http.setDoInput(true);
     http.connect();
	
     OutputStream out = http.getOutputStream();
     out.write(params.getBytes("UTF-8"));
     out.flush();
     out.close();
	
     InputStream in = http.getInputStream();
     BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
     String valueString = null;
     bufferRes = new StringBuffer();
     while ((valueString = read.readLine()) != null){
         bufferRes.append(valueString);
     }
     in.close();
     if (http != null) {
         // 鍏抽棴杩炴帴
         http.disconnect();
     }
     return bufferRes.toString();
	}
}
 
Example 16
Project: JavAMP   File: RequestHandler.java   View Source Code Vote up 4 votes
/**
 * Sends a HTTP POST request to a specific URL.
 *
 * @param url     The URL to send the request to.
 * @param data    The JSON data to be posted to the panel.
 * @param verbose Whether to be verbose in making the request.
 * @return The response from the web server.
 * @throws java.io.IOException Exception that may be thrown when connecting to given URL.
 */
protected String sendRequest(final URL url, final JSONObject data, final Boolean verbose) throws IOException
{
    // Create new connection to specified URL
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    // Request method, POST in this case as it is a requirement of the AMP API
    connection.setRequestMethod("POST");
    
    // Request properties
    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("charset", "UTF-8");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    
    // Send data through the opened connection
    final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(Charset.forName("UTF-8").encode(data.toString()).array());
    outputStream.flush();
    outputStream.close();
    
    // If verbose then the arguments of the request will be printed to console
    if(verbose)
    {
        final int responseCode = connection.getResponseCode();
        System.out.println("Request sent to URL : " + url);
        System.out.println("JSON Data : " + data.toString());
        System.out.println("Response Code : " + responseCode);
    }
    
    // Get a response from the server
    final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final String response = in.lines().collect(Collectors.joining());
    in.close();
    if(verbose)
    {
        System.out.println(response);
    }
    return response;
}
 
Example 17
Project: OASP   File: OASPVerify.java   View Source Code Vote up 4 votes
@Override
protected OASPStatus doInBackground(Void... params) {
    try {
        // Now post the required info to the OASP server
        JSONObject data = new JSONObject();
        data.put("oasp_ver", oasp_ver);
        data.put("apk_pkg", pkg);
        data.put("apk_ver", vercode);
        data.put("apk_mf_hash", mf_hash);
        data.put("apk_cert", apk_cert);
        data.put("oasp_cert", oasp_cert);

        URL url = new URL(oasp_url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(CON_TIMEOUT);
        conn.setReadTimeout(CON_TIMEOUT);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());
        wr.close();

        // Get the feedback from the OASP server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        JSONObject rst = new JSONObject(result.toString());
        in.close();
        conn.disconnect();

        int status = (int) rst.get("oasp_result");
        if (OASPStatus.contains(status)) {
            return OASPStatus.fromInt(status);
        } else {
            return OASPStatus.COMM_ERROR;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return OASPStatus.COMM_ERROR;
    }
}
 
Example 18
Project: labtablet   File: AsyncRecommendationsLoader.java   View Source Code Vote up 4 votes
@Override
protected ArrayList<Descriptor> doInBackground(Object... params) {

    if (params[0] == null || params[1] == null) {
        error = new Exception("Expected Context, String, String; Got nulls");
        return new ArrayList<>();
    }

    if (!(params[0] instanceof Context &&
            params[1] instanceof String)) {
        error = new Exception("Expected Context, String, String; Got "
                + params[0].getClass() + ", " +
                params[1].getClass());

        return new ArrayList<>();
    }

    Context mContext = (Context) params[0];
    String projectName = (String) params[1];

    try {
        String cookie = DendroAPI.authenticate(mContext);

        DendroConfiguration conf = FileMgr.getDendroConf(mContext);

        URL url = new URL(conf.getAddress() + "/project/" + projectName + "?metadata_recommendations");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("Accept","application/json");
        conn.setDoInput(true);


        /*DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(conf.getAddress() + "/project/" + projectName + "?metadata_recommendations");
        httpget.setHeader("Accept", "application/json");
        httpget.setHeader("Cookie", "connect.sid=" + cookie);

        HttpResponse resp = httpclient.execute(httpget);
        HttpEntity ent = resp.getEntity();*/


        BufferedReader in = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String inputLine;
        StringBuffer response = new StringBuffer();

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

        JSONObject respObject = new JSONObject(response.toString());
        ArrayList<DendroDescriptor> recommendedDendroDescriptors =
                new Gson().fromJson(respObject.get("descriptors").toString(), Utils.ARRAY_DENDRO_DESCRIPTORS);

        ArrayList<Descriptor> recommendedDescriptors = new ArrayList<>();
        for (DendroDescriptor dDesc : recommendedDendroDescriptors) {
            Descriptor desc = new Descriptor();
            desc.setDescriptor(dDesc.getUri());
            desc.setName(dDesc.getShortName());
            desc.setDescription(dDesc.getComment());
            desc.setTag("");
            desc.setValue("");

            recommendedDescriptors.add(desc);
        }

        ChangelogItem log = new ChangelogItem();
        log.setMessage(mContext.getResources().getString(R.string.log_loaded) + " " + projectName + " (" + recommendedDendroDescriptors.size() + ").");
        log.setDate(Utils.getDate());
        log.setTitle(mContext.getResources().getString(R.string.log_loaded));
        ChangelogManager.addLog(log, mContext);

        return recommendedDescriptors;

    } catch (Exception e) {
        error = e;
        return new ArrayList<>();
    }
}
 
Example 19
Project: Codeforces   File: HurlStack.java   View Source Code Vote up 4 votes
@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection,
        Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.addRequestProperty(HEADER_CONTENT_TYPE,
                        request.getPostBodyContentType());
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(postBody);
                out.close();
            }
            break;
        case Method.GET:
            // Not necessary to set the request method because connection defaults to GET but
            // being explicit here.
            connection.setRequestMethod("GET");
            break;
        case Method.DELETE:
            connection.setRequestMethod("DELETE");
            break;
        case Method.POST:
            connection.setRequestMethod("POST");
            addBodyIfExists(connection, request);
            break;
        case Method.PUT:
            connection.setRequestMethod("PUT");
            addBodyIfExists(connection, request);
            break;
        case Method.HEAD:
            connection.setRequestMethod("HEAD");
            break;
        case Method.OPTIONS:
            connection.setRequestMethod("OPTIONS");
            break;
        case Method.TRACE:
            connection.setRequestMethod("TRACE");
            break;
        case Method.PATCH:
            connection.setRequestMethod("PATCH");
            addBodyIfExists(connection, request);
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example 20
Project: letv   File: AppbarActivity.java   View Source Code Vote up 4 votes
protected byte[] a(String... strArr) {
    try {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(strArr[0]).openConnection();
            httpURLConnection.setConnectTimeout(5000);
            try {
                httpURLConnection.setRequestMethod("GET");
                try {
                    InputStream inputStream = httpURLConnection.getInputStream();
                    try {
                        if (httpURLConnection.getResponseCode() == 200) {
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            byte[] bArr = new byte[1024];
                            while (true) {
                                int read = inputStream.read(bArr);
                                if (read != -1) {
                                    byteArrayOutputStream.write(bArr, 0, read);
                                } else {
                                    byteArrayOutputStream.close();
                                    inputStream.close();
                                    return byteArrayOutputStream.toByteArray();
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                } catch (IOException e2) {
                    e2.printStackTrace();
                    return null;
                }
            } catch (ProtocolException e3) {
                e3.printStackTrace();
                return null;
            }
        } catch (IOException e22) {
            e22.printStackTrace();
            return null;
        }
    } catch (MalformedURLException e4) {
        e4.printStackTrace();
        return null;
    }
}