List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*from w w w . j ava 2s.co m*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return */ @Deprecated public static String uploadMedia(String access_token, String msgType, String localFile) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + msgType; String local_url = localFile; try { File file = new File(local_url); if (!file.exists() || !file.isFile()) { log.error("==" + local_url); return null; } URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // Post????get? con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post?? // ? con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY); // con.setRequestProperty("Content-Type", // "multipart/mixed; boundary=" + BOUNDARY); // con.setRequestProperty("content-type", "text/html"); // ? // StringBuilder sb = new StringBuilder(); sb.append("--"); // ////////? sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // ? OutputStream out = new DataOutputStream(con.getOutputStream()); out.write(head); // DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ?? out.write(foot); out.flush(); out.close(); /** * ????,????? */ // con.getResponseCode(); try { // BufferedReader???URL? StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); buffer.append(line); } String respStr = buffer.toString(); log.debug("==respStr==" + respStr); try { JSONObject dataJson = JSONObject.parseObject(respStr); media_id = dataJson.getString("media_id"); } catch (Exception e) { log.error("==respStr==" + respStr, e); try { JSONObject dataJson = JSONObject.parseObject(respStr); return dataJson.getString("errcode"); } catch (Exception e1) { } } } catch (Exception e) { log.error("??POST?" + e); } } catch (Exception e) { log.error("?!=" + local_url); log.error("?!", e); } finally { } return media_id; }
From source file:com.androidex.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * /*from w w w .java 2 s. c om*/ * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:com.volley.air.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * //from w w w.j ava 2 s . c o m * @param connection * The Connection to perform the multi part request * @param request * The params to add to the Multi Part request * The files to upload * @throws ProtocolException */ private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request) throws IOException, ProtocolException { final String charset = ((MultiPartRequest<?>) request).getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = ((MultiPartRequest<?>) request).getMultipartParams(); Map<String, String> filesToUpload = ((MultiPartRequest<?>) request).getFilesToUpload(); if (((MultiPartRequest<?>) request).isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end ProgressListener progressListener; progressListener = (ProgressListener) request; PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (Entry<String, MultiPartParam> entry : multipartParams.entrySet()) { MultiPartParam param = entry.getValue(); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, entry.getKey())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } for (Entry<String, String> entry : filesToUpload.entrySet()) { File file = new File(entry.getValue()); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, entry.getKey(), file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength; byte[] buffer = new byte[1024]; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; progressListener.onProgress(transferredBytes, totalSize); } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
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 a2 s . 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:com.alibaba.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post/* w w w . jav a2s.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 { 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.melniqw.instagramsdk.Network.java
private static String sendDummyRequest(String url, String body, Request request) throws IOException { HttpURLConnection connection = null; try {// w w w .jav a2 s . co m connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); if (request == Request.GET) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else if (request == Request.POST) { connection.setDoOutput(true); connection.setRequestMethod("POST"); } if (REQUEST_ENABLE_COMPRESSION) connection.setRequestProperty("Accept-Encoding", "gzip"); if (request == Request.POST) connection.getOutputStream().write(body.getBytes("utf-8")); int code = connection.getResponseCode(); System.out.println(TAG + " responseCode = " + code); //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation if (code == -1) throw new WrongResponseCodeException("Network error"); // ? 200 //on error can also read error stream from connection. InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192); String encoding = connection.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) inputStream = new GZIPInputStream(inputStream); String response = Utils.convertStreamToString(inputStream); System.out.println(TAG + " response = " + response); return response; } finally { if (connection != null) connection.disconnect(); } }
From source file:com.omertron.themoviedbapi.tools.WebBrowser.java
public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException { StringWriter content = null;//from w ww .j a v a2 s. c o m try { content = new StringWriter(); BufferedReader in = null; HttpURLConnection cnx = null; OutputStreamWriter wr = null; try { cnx = (HttpURLConnection) openProxiedConnection(url); // If we get a null connection, then throw an exception if (cnx == null) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, "No HTTP connection could be made.", url); } if (isDeleteRequest) { cnx.setDoOutput(true); cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cnx.setRequestMethod("DELETE"); } sendHeader(cnx); if (StringUtils.isNotBlank(jsonBody)) { cnx.setDoOutput(true); wr = new OutputStreamWriter(cnx.getOutputStream()); wr.write(jsonBody); } readHeader(cnx); // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error if (cnx.getResponseCode() >= 400) { in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx))); } else { in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); } String line; while ((line = in.readLine()) != null) { content.write(line); } } finally { if (wr != null) { wr.flush(); wr.close(); } if (in != null) { in.close(); } if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } return content.toString(); } catch (IOException ex) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex); } finally { if (content != null) { try { content.close(); } catch (IOException ex) { LOG.debug("Failed to close connection: " + ex.getMessage()); } } } }
From source file:com.kiwiteam.nomiddleman.TourPageActivity.java
/** * Checks if link is active// w w w . ja va 2s . co m * @param urlString * @return * @throws MalformedURLException * @throws IOException */ public static int getResponseCode(String urlString) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); huc.connect(); return huc.getResponseCode(); }
From source file:com.gmobi.poponews.util.HttpHelper.java
private static Response doRequest(String url, Object raw, int method) { disableSslCheck();//from w w w.ja v a2 s .c om boolean isJson = raw instanceof JSONObject; String body = raw == null ? null : raw.toString(); Response response = new Response(); HttpURLConnection connection = null; try { URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (method == HTTP_POST) connection.setRequestMethod("POST"); if (body != null) { if (isJson) { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); } OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(body); osw.flush(); osw.close(); } InputStream in = connection.getInputStream(); response.setBody(FileHelper.readText(in, "UTF-8")); response.setStatusCode(connection.getResponseCode()); in.close(); connection.disconnect(); connection = null; } catch (Exception e) { Logger.error(e); try { if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) { response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8")); } } catch (Exception ex) { Logger.error(ex); } } return response; }
From source file:org.akita.io.HttpInvoker.java
/** * post with files using URLConnection Impl * @param actionUrl URL to post//from w w w .j a va2s.com * @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); } }