本文整理汇总了Java中java.net.HttpURLConnection.setRequestMethod方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setRequestMethod方法的具体用法?Java HttpURLConnection.setRequestMethod怎么用?Java HttpURLConnection.setRequestMethod使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.setRequestMethod方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testWriteLessThanContentLength
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@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();
}
示例2: rename
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* <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;
}
示例3: createSymLink
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* <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;
}
示例4: getAllMenuJson
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 네트워크 연결을 통한 모든 메뉴 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;
}
示例5: testWriteAfterConnect
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 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());
}
}
示例6: test
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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);
}
}
示例7: buildPost
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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;
}
示例8: download
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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();
}
示例9: downloadPartially
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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);
}
}
示例10: syncGet
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 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;
}
示例11: test
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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();
}
}
示例12: createConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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;
}
示例13: main
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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);
}
示例14: streamedBodyIsRetriedOnHttp2Shutdown
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@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());
}
示例15: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丳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();
}
}