本文整理汇总了Java中java.net.HttpURLConnection.HTTP_CREATED属性的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.HTTP_CREATED属性的具体用法?Java HttpURLConnection.HTTP_CREATED怎么用?Java HttpURLConnection.HTTP_CREATED使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.HTTP_CREATED属性的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: importToCloudCard
private static String importToCloudCard(CardHolder cardHolder, Properties properties) {
try {
URL url = new URL(properties.getProperty(BASE_URL) + "/api/people");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
setConnectionHeaders(connection, properties);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(cardHolder.toJSON().getBytes());
outputStream.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
return "Failed : HTTP error code : " + connection.getResponseCode();
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return "Success";
}
示例2: sendRequest
private boolean sendRequest(String url, String content) {
LogUtils.d(TAG, "------url = " + url + "\ncontent = " + content);
try {
HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
.setRequestMethod("POST")
.setHeader("Content-Type", "application/x-gzip")
.setHeader("Content-Encoding", "gzip")
.setRequestBody(content)
.setGzip(true)
.build();
int responseCode = httpConn.getResponseCode();
boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
return successful;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
示例3: sendRequest
private boolean sendRequest(String url, String content) {
LogUtils.d(TAG, "----url:" + url + "\tcontent:" + content);
try {
HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
.setRequestMethod("POST")
.setHeader("Content-Type", "application/json")
.setRequestBody(content)
.build();
int responseCode = httpConn.getResponseCode();
boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
return successful;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
示例4: inspect
public void inspect() throws IOException {
final BlockInfo blockInfo = info.getBlock(blockIndex);
boolean isServerCancelled = false;
ResumeFailedCause resumeFailedCause = null;
final int code = connected.getResponseCode();
final String etag = info.getEtag();
final String newEtag = connected.getResponseHeaderField("Etag");
do {
if (code == HttpURLConnection.HTTP_PRECON_FAILED) {
resumeFailedCause = RESPONSE_PRECONDITION_FAILED;
break;
}
if (!Util.isEmpty(etag) && !Util.isEmpty(newEtag) && !newEtag.equals(etag)) {
// etag changed.
// also etag changed is relate to HTTP_PRECON_FAILED
resumeFailedCause = RESPONSE_ETAG_CHANGED;
break;
}
if (code == HttpURLConnection.HTTP_CREATED && blockInfo.getCurrentOffset() != 0) {
// The request has been fulfilled and has resulted in one or more new resources
// being created.
// mark this case is precondition failed for
// 1. checkout whether accept partial
// 2. 201 means new resources so range must be from beginning otherwise it can't
// match local range.
resumeFailedCause = RESPONSE_CREATED_RANGE_NOT_FROM_0;
break;
}
if (code == HttpURLConnection.HTTP_RESET && blockInfo.getCurrentOffset() != 0) {
resumeFailedCause = RESPONSE_RESET_RANGE_NOT_FROM_0;
break;
}
if (code != HttpURLConnection.HTTP_PARTIAL && code != HttpURLConnection.HTTP_OK) {
isServerCancelled = true;
break;
}
if (code == HttpURLConnection.HTTP_OK && blockInfo.getCurrentOffset() != 0) {
isServerCancelled = true;
break;
}
} while (false);
if (resumeFailedCause != null) {
// resume failed, relaunch from beginning.
throw new ResumeFailedException(resumeFailedCause);
}
if (isServerCancelled) {
// server cancelled, end task.
throw new ServerCancelledException(code, blockInfo.getCurrentOffset());
}
}
示例5: urlRequest
/**
* @param url 请求URL
* @param method 请求URL
* @param param json参数(post|put)
* @param auth 认证(username+:+password)
* @return 返回结果
*/
public static String urlRequest(String url,String method,String param,String auth){
String result = null;
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(60*1000);
connection.setRequestMethod(method.toUpperCase());
if(auth!=null&&!"".equals(auth)){
String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
connection.setRequestProperty("Authorization", authorization);
}
if(param!=null&&!"".equals(param)){
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.write(param.getBytes(Consts.UTF_8));
dos.flush();
dos.close();
}else{
connection.connect();
}
if(connection.getResponseCode()==HttpURLConnection.HTTP_OK||connection.getResponseCode()==HttpURLConnection.HTTP_CREATED){
InputStream in = connection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while((len=in.read(buff, 0, buff.length))>0){
out.write(buff, 0, len);
}
byte[] data = out.toByteArray();
in.close();
result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
}else{
result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
}
connection.disconnect();
}catch (Exception e) {
logger.error("--http request error !",e);
}
return result;
}
示例6: doInBackground
@Override
protected UserSessionData doInBackground(String... args) {
try {
HttpURLConnection connect = (HttpURLConnection) new URL(context.getString(R.string.url_connect)).openConnection();
connect.setRequestMethod("POST");
connect.setDoOutput(true);
String inputString = args[0] + ":" + args[1];
String credentials = Base64.encodeToString(inputString.getBytes(), Base64.NO_WRAP);
String authentication = "basic " + credentials;
connect.setRequestProperty("Authorization", authentication);
JSONObject jsonObject = new JSONObject();
jsonObject.put("client_id", context.getString(R.string.client_id));
jsonObject.put("client_secret", context.getString(R.string.client_secret));
jsonObject.put("note", context.getString(R.string.note));
JSONArray jsonArray = new JSONArray();
jsonArray.put("repo");
jsonArray.put("user");
jsonObject.put("scopes", jsonArray);
OutputStream outputStream = connect.getOutputStream();
Log.v(TAG, "request body = " + jsonObject.toString());
outputStream.write(jsonObject.toString().getBytes());
connect.connect();
int responseCode = connect.getResponseCode();
Log.v(TAG, "responseCode = " + responseCode);
if (responseCode != HttpURLConnection.HTTP_CREATED) {
return null;
}
InputStream inputStream = connect.getInputStream();
String response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Log.v(TAG, "response = " + response);
JSONObject jObj = new JSONObject(response);
HttpURLConnection reconnect = (HttpURLConnection) new URL(context.getString(R.string.url_login_data)).openConnection();
reconnect.setRequestMethod("GET");
authentication = "token " + jObj.getString("token");
reconnect.setRequestProperty("Authorization", authentication);
reconnect.connect();
responseCode = connect.getResponseCode();
Log.v(TAG, "responseCode = " + responseCode);
inputStream = reconnect.getInputStream();
response = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Log.v(TAG, "response = " + response);
JSONObject object = new JSONObject(response);
UserSessionData data = new UserSessionData(jObj.getString("id"), credentials, jObj.getString("token"), object.getString("login"));
return data;
} catch (Exception e) {
Log.e(TAG, "Login failed", e);
return null;
}
}
示例7: post
public static String post(
String targetURL,
String payload,
String username,
String password)
throws IOException
{
final HttpURLConnection conn = getHttpConnection("POST", targetURL, username, password);
if (null == conn) {
if (ConstantsUI.DEBUG_MODE) {
Log.d(ConstantsUI.TAG, "Error get connection object: " + targetURL);
}
return "0";
}
conn.setRequestProperty("Content-type", "application/json");
// Allow Outputs
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(payload);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK
&& responseCode != HttpURLConnection.HTTP_CREATED) {
if (ConstantsUI.DEBUG_MODE) {
Log.d(
ConstantsUI.TAG,
"Problem execute post: " + targetURL + " HTTP response: " + responseCode);
}
return responseCode + "";
}
return responseToString(conn.getInputStream());
}
示例8: sendPost
private String sendPost(Pair<String, String> data) {
StringBuilder content = new StringBuilder();
try {
// Send POST request
URL url = new URL(data.first);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(data.second.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED &&
conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String line;
while ((line = br.readLine()) != null)
content.append(line + "\n");
conn.disconnect();
return content.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
示例9: extractToken
/**
* Helper method that extracts an authentication token received from a connection.
* <p>
* This method is used by {@link Authenticator} implementations.
*
* @param conn connection to extract the authentication token from.
* @param token the authentication token.
*
* @throws IOException if an IO error occurred.
* @throws AuthenticationException if an authentication exception occurred.
*/
public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException {
int respCode = conn.getResponseCode();
if (respCode == HttpURLConnection.HTTP_OK
|| respCode == HttpURLConnection.HTTP_CREATED
|| respCode == HttpURLConnection.HTTP_ACCEPTED) {
Map<String, List<String>> headers = conn.getHeaderFields();
List<String> cookies = headers.get("Set-Cookie");
if (cookies != null) {
for (String cookie : cookies) {
if (cookie.startsWith(AUTH_COOKIE_EQ)) {
String value = cookie.substring(AUTH_COOKIE_EQ.length());
int separator = value.indexOf(";");
if (separator > -1) {
value = value.substring(0, separator);
}
if (value.length() > 0) {
token.set(value);
}
}
}
}
} else {
token.set(null);
throw new AuthenticationException("Authentication failed, status: " + conn.getResponseCode() +
", message: " + conn.getResponseMessage());
}
}
示例10: onPostExecute
@Override
protected void onPostExecute(Intent intent) {
super.onPostExecute(intent);
mCallbacks.postExecute(intent);
if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
//Toast.makeText(context, jsonParam.toString(), Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(context, "Something wrong with Internet connection", Toast.LENGTH_SHORT).show();
}
EventHub.nAsyncTasks.remove(this);
}
示例11: postExecute
@Override
public void postExecute(Intent intent) {
int responseCode = intent.getIntExtra(EventHub.HTTP_CODE, 0);
if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
//Toast.makeText(context, jsonParam.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something wrong with Internet connection", Toast.LENGTH_SHORT).show();
}
}
示例12: report
private void report(String filename, String key) {
//3、上报服务器
HttpURLConnection url = null;
boolean successful = false;
try {
JSONObject parameters = new JSONObject();
parameters.put("app_bundle_id", AppBean.APP_PACKAGE);
parameters.put("app_name", AppBean.APP_NAME);
parameters.put("app_version", AppBean.APP_VERSION);
parameters.put("device_model", AppBean.PHONE_MODEL);
parameters.put("os_platform", AppBean.ANDROID_PLATFORM);
parameters.put("os_version", AppBean.ANDROID_VERSION);
parameters.put("os_build", AppBean.ANDROID_BUILD);
parameters.put("sdk_version", AppBean.SDK_VERSION);
parameters.put("sdk_id", AppBean.SDK_ID);
parameters.put("device_id", AppBean.DEVICE_IDENTIFIER);
parameters.put("tag", AppBean.APP_TAG);
parameters.put("manufacturer", AppBean.PHONE_MANUFACTURER);
parameters.put("start_time", mStartTime);
parameters.put("end_time", mEndTime);
parameters.put("log_key", key);
parameters.put("log_tags", "");
parameters.put("error_count", 0);
url = new HttpURLConnectionBuilder(Configuration.getLogcatUrl())
.setRequestMethod("POST")
.setHeader("Content-Type", "application/json")
.setRequestBody(parameters.toString())
.build();
int responseCode = url.getResponseCode();
successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
LogUtils.e(TAG, "----" + e.toString());
e.printStackTrace();
} finally {
if (url != null) {
url.disconnect();
}
if (successful) {
mContext.deleteFile(filename);
} else {
LogUtils.d("-----Transmission failed, will retry on next register() call");
}
}
}
示例13: sendRequest
private static void sendRequest(WeakReference<Context> weakContext, String key, JSONObject bean, String list) {
//3、上报服务器
HttpURLConnection url = null;
boolean successful = false;
try {
JSONObject parameters = new JSONObject();
parameters.put("app_bundle_id", AppBean.APP_PACKAGE);
parameters.put("app_name", AppBean.APP_NAME);
parameters.put("app_version", AppBean.APP_VERSION);
parameters.put("device_model", AppBean.PHONE_MODEL);
parameters.put("os_platform", AppBean.ANDROID_PLATFORM);
parameters.put("os_version", AppBean.ANDROID_VERSION);
parameters.put("os_build", AppBean.ANDROID_BUILD);
parameters.put("sdk_version", AppBean.SDK_VERSION);
parameters.put("sdk_id", AppBean.SDK_ID);
parameters.put("device_id", AppBean.DEVICE_IDENTIFIER);
parameters.put("tag", AppBean.APP_TAG);
parameters.put("report_uuid", bean.optString(FIELD_REPORT_UUID));
parameters.put("crash_log_key", key);
parameters.put("manufacturer", AppBean.PHONE_MANUFACTURER);
parameters.put("start_time", bean.optString(FILELD_START_TIME));
parameters.put("crash_time", bean.optString(FILELD_CRASH_TIME));
url = new HttpURLConnectionBuilder(Configuration.getCrashUrl())
.setRequestMethod("POST")
.setHeader("Content-Type", "application/json")
.setRequestBody(parameters.toString())
.build();
int responseCode = url.getResponseCode();
successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
} catch (Exception e) {
LogUtils.e(TAG, "----" + e.toString());
e.printStackTrace();
} finally {
if (url != null) {
url.disconnect();
}
if (successful) {
deleteStackTrace(weakContext, list);
} else {
LogUtils.d("-----Transmission failed, will retry on next register() call");
}
}
}
示例14: isValidStatus
boolean isValidStatus(int status) {
return status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_CREATED;
}