List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.sunchenbin.store.feilong.core.net.URLConnectionUtil.java
/** * Prepare connection./*from w w w . j av a2s .c om*/ * * @param httpURLConnection * the http url connection * @param httpRequest * the http request * @param useConnectionConfig * the use connection config * @throws IOException * the IO exception * @since 1.4.0 * @see "org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(HttpURLConnection, String)" */ private static void prepareConnection(HttpURLConnection httpURLConnection, HttpRequest httpRequest, ConnectionConfig useConnectionConfig) throws IOException { HttpMethodType httpMethodType = httpRequest.getHttpMethodType(); // ?HttpUrlConnectionconnectTimeout httpURLConnection.setConnectTimeout(useConnectionConfig.getConnectTimeout()); httpURLConnection.setReadTimeout(useConnectionConfig.getReadTimeout()); httpURLConnection.setRequestMethod(httpMethodType.getMethod().toUpperCase());//?,? java.net.ProtocolException: Invalid HTTP method: get httpURLConnection.setDoOutput(HttpMethodType.POST == httpMethodType); Map<String, String> headerMap = httpRequest.getHeaderMap(); if (null != headerMap) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue()); } } }
From source file:com.headswilllol.basiclauncher.Launcher.java
public static int getFileSize(URL url) { HttpURLConnection conn = null; try {//from ww w. j av a 2s .co m conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); // joke's on you if the server doesn't specify conn.getInputStream(); return conn.getContentLength(); } catch (Exception e) { return -1; } finally { if (conn != null) conn.disconnect(); } }
From source file:br.bireme.tb.URLS.java
/** * Given an url, loads its content (GET - method) * @param url url to be loaded/* www . j a va2 s. c om*/ * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPageGet(final URL url) throws IOException { if (url == null) { throw new NullPointerException("url"); } System.out.print("loading page (GET) : [" + url + "]"); HttpURLConnection.setFollowRedirects(false); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); connection.setRequestProperty("User-Agent", "curl/7.29.0"); connection.setRequestProperty("Accept", "*/*"); connection.connect(); int respCode = connection.getResponseCode(); final StringBuilder builder = new StringBuilder(); String location = url.toString(); while ((respCode >= 300) && (respCode <= 399)) { location = connection.getHeaderField("Location"); connection = (HttpURLConnection) new URL(location).openConnection(); respCode = connection.getResponseCode(); } final boolean respCodeOk = (respCode == 200); final BufferedReader reader; boolean skipLine = false; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING)); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), DEFAULT_ENCODING)); } while (true) { String line = reader.readLine(); if (line == null) { break; } final String line2 = line.trim(); if (line2.startsWith("<!--")) { if (line2.endsWith("-->")) { continue; } skipLine = true; } else if (line2.endsWith("-->")) { skipLine = false; line = ""; } if (!skipLine) { builder.append(line); builder.append("\n"); } } reader.close(); connection.disconnect(); if (!respCodeOk) { throw new IOException("url=[" + url + "]\ncode=" + respCode + "\n" + builder.toString()); } //System.out.print("+"); System.out.println(" - OK"); return new String[] { location, builder.toString() }; }
From source file:net.ftb.util.DownloadUtils.java
/** * @param file - the name of the file, as saved to the repo (including extension) * @param backupLink - the link of the location to backup to if the repo copy isn't found * @return - the direct static link or the backup link if the file isn't found *//*from w w w. java 2s. c o m*/ public static String getStaticCreeperhostLinkOrBackup(String file, String backupLink) { String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/FTB2/static/" + file; HttpURLConnection connection = null; boolean good = false; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); if (connection.getResponseCode() != 200) { for (String server : downloadServers.values()) { if (connection.getResponseCode() != 200) { resolved = "http://" + server + "/FTB2/static/" + file; connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); } else { if (connection.getResponseCode() == 200) good = true; break; } } } else if (connection.getResponseCode() == 200) { good = true; } } catch (IOException e) { } connection.disconnect(); if (good) return resolved; else { Logger.logWarn("Using backupLink for " + file); return backupLink; } }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
private static String fetch(Uri uri) { HttpURLConnection connection = null; BufferedReader reader = null; String rawJSON = ""; Log.d(TAG, uri.toString());// w ww .j a v a 2 s . c o m try { URL url = new URL(uri.toString()); //java.net Malformed uri exception connection = (HttpURLConnection) url.openConnection(); //java.io. IO exception connection.setRequestMethod("GET"); //java.net.ProtocolException && unnecessary connection.connect(); //java.io.IOExecption InputStream inputStream = connection.getInputStream(); // java.io.IOException StringBuffer stringBuffer = new StringBuffer(); if (inputStream == null) { return rawJSON; } reader = new BufferedReader(new InputStreamReader(inputStream)); //Make the string more readable String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line + "\n"); } rawJSON = stringBuffer.toString(); Log.d(TAG + "doInBackground", rawJSON); } catch (IOException e) { Log.e(TAG, "Error ", e); e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(TAG, "Error closing stream", e); } } } return rawJSON; }
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Sends a POST request with an attached object * @param url the url that should be opened * @param params the body parameters//from www.ja v a 2 s. c o m * @param attachment the object to be attached * @return the response * @throws IOException */ public static String postWithAttachment(String url, Map<String, String> params, Object attachment) throws IOException { String boundary = generateBoundaryString(10); URL servUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB); conn.setRequestMethod("POST"); String contentType = "multipart/form-data; boundary=" + boundary; conn.setRequestProperty("Content-Type", contentType); byte[] body = generatePostBody(params, attachment, boundary); conn.setDoOutput(true); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(body); InputStream is = null; try { is = conn.getInputStream(); } catch (FileNotFoundException e) { is = conn.getErrorStream(); } catch (Exception e) { int statusCode = conn.getResponseCode(); Log.e("Response code", "" + statusCode); return conn.getResponseMessage(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String l; while ((l = r.readLine()) != null) sb.append(l).append('\n'); out.close(); is.close(); if (conn != null) conn.disconnect(); return sb.toString(); }
From source file:com.alibaba.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post/*from w w w. java 2 s. c om*/ * @param params params to post * @param files files to post, support multi-files * @return response in String format * @throws IOException */ public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params, Map<String, File> files) throws AkInvokeException { try { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(60 * 1000); conn.setDoInput(true); // permit input conn.setDoOutput(true); // permit output conn.setUseCaches(false); conn.setRequestMethod("POST"); // Post Method conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // firstly string params to add StringBuilder sb = new StringBuilder(); for (NameValuePair nameValuePair : params) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(nameValuePair.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // send files secondly if (files != null) { int num = 0; for (Map.Entry<String, File> file : files.entrySet()) { num++; if (file.getKey() == null || file.getValue() == null) continue; else { if (!file.getValue().exists()) { throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND, "The file to upload is not found."); } } StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file" + num + "\"; filename=\"" + file.getKey() + "\"" + 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()); } } // request end flag byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // get response code int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192); String line = null; while ((line = reader.readLine()) != null) { sb2.append(line + "\n"); } reader.close(); } outStream.close(); conn.disconnect(); return sb2.toString(); } catch (IOException ioe) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe); } }
From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java
/** * ?/*from w w w . ja va 2s .c om*/ * @param postUrl ? * @param param ? * @param method * @return null */ public static String request(String postUrl, String param, String method) { URL url; try { url = new URL(postUrl); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); // ??) conn.setReadTimeout(30000); // ????) conn.setDoOutput(true); // post??http?truefalse conn.setDoInput(true); // ?httpUrlConnectiontrue conn.setUseCaches(false); // Post ? conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod(method);// "POST"GET conn.setRequestProperty("Content-Length", param.length() + ""); String encode = "utf-8"; OutputStreamWriter out = null; out = new OutputStreamWriter(conn.getOutputStream(), encode); out.write(param); out.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } // ?? BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = ""; StringBuffer strBuf = new StringBuffer(); while ((line = in.readLine()) != null) { strBuf.append(line).append("\n"); } in.close(); out.close(); return strBuf.toString(); } catch (MalformedURLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.jooketechnologies.network.ServerUtilities.java
static JSONObject post(String endpoint, int action, Map<String, String> params) { URL url;/*from w w w . ja v a 2s. c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); InputStream is = conn.getInputStream(); if (status != 200) { if (conn != null) { conn.disconnect(); } } else { JSONObject jsonObject = streamToString(is); return jsonObject; } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:org.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post//from ww w. j a v a 2s . c o m * @param params params to post * @param files files to post, support multi-files * @return response in String format * @throws IOException */ public static String postWithFilesUsingURLConnection(String actionUrl, ArrayList<NameValuePair> params, Map<String, File> files) throws AkInvokeException { try { Log.v(TAG, "post:" + actionUrl); if (params != null) { Log.v(TAG, "params:====================="); for (NameValuePair nvp : params) { Log.v(TAG, nvp.getName() + "=" + nvp.getValue()); } Log.v(TAG, "params end:====================="); } String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(60 * 1000); conn.setDoInput(true); // permit input conn.setDoOutput(true); // permit output conn.setUseCaches(false); conn.setRequestMethod("POST"); // Post Method conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // firstly string params to add StringBuilder sb = new StringBuilder(); for (NameValuePair nameValuePair : params) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(nameValuePair.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // send files secondly if (files != null) { int num = 0; for (Map.Entry<String, File> file : files.entrySet()) { num++; if (file.getKey() == null || file.getValue() == null) continue; else { if (!file.getValue().exists()) { throw new AkInvokeException(AkInvokeException.CODE_FILE_NOT_FOUND, "The file to upload is not found."); } } StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getKey() + "\"" + 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()); } } // request end flag byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // get response code int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"), 8192); String line = null; while ((line = reader.readLine()) != null) { sb2.append(line + "\n"); } reader.close(); } outStream.close(); conn.disconnect(); Log.v(TAG, "response:" + sb2.toString()); return sb2.toString(); } catch (IOException ioe) { throw new AkInvokeException(AkInvokeException.CODE_IO_EXCEPTION, "IO Exception", ioe); } }