本文整理汇总了Java中java.net.HttpURLConnection.setUseCaches方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.setUseCaches方法的具体用法?Java HttpURLConnection.setUseCaches怎么用?Java HttpURLConnection.setUseCaches使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.setUseCaches方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createHttpUrlConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
static HttpURLConnection createHttpUrlConnection(
String fullPath, String httpMethod, boolean ssl, int timeoutSeconds)
throws IOException {
URL url = new URL(fullPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (ssl) {
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
((HttpsURLConnection) urlConnection).setSSLSocketFactory(socketFactory);
}
urlConnection.setReadTimeout(timeoutSeconds * 1000);
urlConnection.setConnectTimeout(timeoutSeconds * 1000);
urlConnection.setRequestMethod(httpMethod);
urlConnection.setDoOutput(!"GET".equals(httpMethod));
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setInstanceFollowRedirects(true);
Context context = Leanplum.getContext();
urlConnection.setRequestProperty("User-Agent",
getApplicationName(context) + "/" + getVersionName() + "/" + Request.appId() + "/" +
Constants.CLIENT + "/" + Constants.LEANPLUM_VERSION + "/" + getSystemName() + "/" +
getSystemVersion() + "/" + Constants.LEANPLUM_PACKAGE_IDENTIFIER);
return urlConnection;
}
示例2: sendPacket
import java.net.HttpURLConnection; //导入方法依赖的package包/类
protected Object sendPacket(Map<Object,Object> packet) throws IOException {
String json=JSON.stringify(packet);
URL obj=new URL("http://"+IP+":"+PORT+"/run.json");
HttpURLConnection conn=(HttpURLConnection)obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-type","text/plain");
conn.setRequestProperty("Accept","application/json");
conn.setConnectTimeout(0);
conn.getOutputStream().write(json.getBytes(Charset.forName("UTF-8")));
conn.getOutputStream().close();
ByteArrayOutputStream response=new ByteArrayOutputStream();
int readed;
byte chunk[]=new byte[1024*1024];
while((readed=conn.getInputStream().read(chunk))!=-1){
response.write(chunk,0,readed);
System.out.println("Read");
}
conn.getInputStream().close();
String response_s=response.toString("UTF-8");
System.out.println("<<< "+response_s);
return JSON.parse(response_s);
}
示例3: checkRequestCaching
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Helper method to make a request with cache enabled or disabled, and check
* whether the request is successful.
* @param requestUrl request url.
* @param cacheSetting indicates cache should be used.
* @param outcome indicates request is expected to be successful.
*/
private void checkRequestCaching(String requestUrl,
CacheSetting cacheSetting,
ExpectedOutcome outcome) throws Exception {
URL url = new URL(requestUrl);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setUseCaches(cacheSetting == CacheSetting.USE_CACHE);
if (outcome == ExpectedOutcome.SUCCESS) {
assertEquals(200, connection.getResponseCode());
assertEquals("this is a cacheable file\n", TestUtil.getResponseAsString(connection));
} else {
try {
connection.getResponseCode();
fail();
} catch (IOException e) {
// Expected.
}
}
connection.disconnect();
}
示例4: setHttpRequest
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 设置http请求默认属性
*
* @param httpConnection
*/
protected void setHttpRequest(HttpURLConnection httpConnection) {
//设置连接超时时间
httpConnection.setConnectTimeout(this.timeOut * 1000);
//User-Agent
httpConnection.setRequestProperty("User-Agent",
HttpClient.USER_AGENT_VALUE);
//不使用缓存
httpConnection.setUseCaches(false);
//允许输入输出
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
}
示例5: RequestJsonPost
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static String RequestJsonPost(MsgTO msgto) {
String json = JSON.toJSONString(msgto);
String strResponse = null;
try {
URL url1 = new URL(msgto.getUrl());
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();// 建立http连接
conn.setDoOutput(true);// 设置允许输出
conn.setDoInput(true);
conn.setUseCaches(false);// 设置不用缓存
conn.setRequestMethod("POST"); // 设置传递方式
conn.setRequestProperty("Connection", "Keep-Alive");// 设置维持长连接
conn.setRequestProperty("Charset", "UTF-8");// 设置文件字符集
byte[] data = json.getBytes();// 转换为字节数组
conn.setRequestProperty("Content-Length", String.valueOf(data.length));// 设置文件长度
conn.setRequestProperty("Content-Type", "application/json");// 设置文件类型
conn.connect(); // 开始连接请求
OutputStream out = conn.getOutputStream();
out.write(json.getBytes("utf-8"));// 写入请求的字符串
out.flush();
out.close();
// System.out.println(conn.getResponseCode());
// 请求返回的状态
if (conn.getResponseCode() == 200) {
// System.out.println("连接成功");
InputStream in = conn.getInputStream();// 请求返回的数据
try {
byte[] data1 = new byte[in.available()];
in.read(data1);
strResponse = new String(data1, "utf-8");// 转成字符串
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
System.out.println("no++");
}
} catch (Exception e) {
e.printStackTrace();
}
return strResponse;
}
示例6: prepareConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
connection.setUseCaches(false);
}
示例7: 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;
}
示例8: httpPost
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 指定ContentType调用接口
*
* @param url
* @param body
* @param ContentType
* @return
*/
public static String httpPost(String url, String body, String ContentType) {
String bs = null;
try {
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setReadTimeout(CONNECTION_TIME_OUT_TIME);
conn.setConnectTimeout(CONNECTION_TIME_OUT_TIME);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", ContentType);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(body.toString().getBytes());
outStream.flush();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int n;
while ((n = in.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
byte[] b = out.toByteArray();
in.close();
bs = new String(b);
}
outStream.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return bs;
}
示例9: postLogin
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void postLogin(URL endpointUrl, Map<String, String> params)
throws IOException, BadCredentialsException
{
HttpURLConnection conn = (HttpURLConnection) new URL(endpointUrl, "session").openConnection();
String postData = URLUtils.getParameterString(params);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
byte[] postBytes = postData.getBytes(StandardCharsets.UTF_8);
conn.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
conn.setUseCaches(false);
try( OutputStream wr = conn.getOutputStream() )
{
wr.write(postBytes);
}
int code = conn.getResponseCode();
if( code == 403 || code == 401 )
{
throw new BadCredentialsException("Bad credentials");
}
else if (code != 200)
{
throw new RuntimeException("Error launching console: " + code);
}
}
示例10: postLogin
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 登陆获取 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;
}
示例11: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Submits an HTTP POST request to the given URL.
*
* @param url the URL to receive the POST request
* @return the reply
* @throws IOException in case of failure
*/
public InputStream post(URL url) throws IOException {
writeEnd();
OutputStream out = null;
try {
final HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
http.setRequestProperty("Content-Length", String.valueOf(bytes.size()));
out = http.getOutputStream();
bytes.writeTo(out);
out.close();
return http.getInputStream();
}
finally {
IOUtils.closeQuietly(out);
}
}
示例12: configUrlConnection
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static void configUrlConnection(HttpURLConnection urlConnection) {
urlConnection.setReadTimeout(TIMEOUT);
urlConnection.setConnectTimeout(TIMEOUT);
urlConnection.setUseCaches(false);
}
示例13: post
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param url Service net address
* @param params text content
* @param files pictures
* @return String result of Service response
* @throws IOException
*/
public static String post(String url, Map<String, String> params, Map<String, File> files)
throws IOException {
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ file.getValue().getName() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
InputStream in = conn.getInputStream();
StringBuilder sb2 = new StringBuilder();
if (res == 200) {
int ch;
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return sb2.toString();
}
示例14: run
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
public void run() {
try {
String sb = csebase.getServiceUrl() +"/" + ServiceAEName + "/" + container_name;
URL mUrl = new URL(sb);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("Content-Type", "application/vnd.onem2m-res+xml;ty=4");
conn.setRequestProperty("locale", "ko");
conn.setRequestProperty("X-M2M-RI", "12345");
conn.setRequestProperty("X-M2M-Origin", ae.getAEid() );
String reqContent = contentinstance.makeXML();
conn.setRequestProperty("Content-Length", String.valueOf(reqContent.length()));
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(reqContent.getBytes());
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String resp = "";
String strLine="";
while ((strLine = in.readLine()) != null) {
resp += strLine;
}
if (resp != "") {
receiver.getResponseBody(resp);
}
conn.disconnect();
} catch (Exception exp) {
LOG.log(Level.SEVERE, exp.getMessage());
}
}
示例15: postReq
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void postReq(File f) throws Exception
{
String url = "http://danieloluwadare.com/write.php";
url = "http://ec2-52-15-200-194.us-east-2.compute.amazonaws.com/write.php";
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
String fileName = f.getName();
fileName = fileName.substring(0, fileName.indexOf("."));
Scanner inp = new Scanner(f);
String content = "";
while( inp.hasNext() )
{
content += inp.nextLine() + "\n";
}
String newContent = "";
for( int i=0; i<content.length(); i++ )
{
if( content.charAt(i) != '"' && content.charAt(i) != '+')
newContent += content.charAt(i);
else
newContent += "\\" + content.charAt(i);
}
/*********************/
/*
school = "neiu";
dept = "304-17";
semester = "spr2017";
test = "midterm";
studentId = "265456";
*/
String urlParameters = "classID=" + MainApp.classID + "&semester=" + MainApp.semester +
"&testDesc=" + MainApp.testDesc + "&studentID=" + MainApp.studentID +
"&school=" + MainApp.school + "&fileName=" + fileName +
"&content=" + content;
byte[] postData = urlParameters.getBytes( java.nio.charset.StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = url;
URL url2 = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url2.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
StringBuilder sb = new StringBuilder();
int HttpResult = conn.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK)
{
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
System.out.println("" + sb.toString());
}
else
{
System.out.println(conn.getResponseMessage());
}
}