List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * //from w ww .j a va 2 s .co m * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {//w w w. j av a 2 s .c o m // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java
/** * Does an HTTP post for a given form data string. * * @param data is the form data string.//from ww w .j a v a 2s . co m * @param url is the url to post to. * @return the return string from the server. * @throws java.io.IOException */ public static String postData(String data, URL url) throws IOException { String result = null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { HttpHelpers.addCommonHeaders(conn); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT); conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); String line; BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn); while ((line = reader.readLine()) != null) { if (result == null) result = line; else result += line; } reader.close(); } catch (IOException ex) { Log.e(TAG, "Failed to read stream data", ex); String error = null; // TODO Am not yet sure if the section below should make it in the production release. // I mainly use it to get details of a failed http request. I get a FileNotFoundException // when actually the url is correct but an exception was thrown at the server and i use this // to get the server call stack for debugging purposes. try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); while ((line = reader.readLine()) != null) { if (error == null) error = line; else error += line; } reader.close(); } catch (Exception e) { Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex); } } return result; }
From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java
private static void loadTestData() throws Exception { String url = "http://localhost:6500/_bulk"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true);//ww w.j a v a2 s . c o m conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt"); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); if (conn.getResponseCode() > 299) { IOUtils.copy(conn.getInputStream(), System.err); throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage()); } client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build()); }
From source file:net.nym.library.http.UploadImagesRequest.java
/** * ???//from ww w . ja va2 s . c o m * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws java.io.IOException */ public static String postFile(String url, Map<String, Object> params, Map<String, File> files) throws IOException { String result = ""; String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; StringBuilder sb = new StringBuilder("?"); for (Map.Entry<String, Object> 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); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString())) .append("&"); } sb.deleteCharAt(sb.length() - 1); URL uri = new URL(url + sb.toString()); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); 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, Object> 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); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); // } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(sb.toString().getBytes()); // ? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sbFile = new StringBuilder(); sbFile.append(PREFIX); sbFile.append(BOUNDARY); sbFile.append(LINEND); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sbFile.append(LINEND); Log.i(sbFile.toString()); outStream.write(sbFile.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 sbResult = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sbResult.append((char) ch); } } result = sbResult.toString(); outStream.close(); conn.disconnect(); return result; }
From source file:circleplus.app.http.AbstractHttpApi.java
private static HttpURLConnection getHttpURLConnection(URL url, int requestMethod, boolean acceptJson) throws IOException { if (D)/* w w w .ja v a2 s. com*/ Log.d(TAG, "execute method: " + requestMethod + " url: " + url.toString() + " accept JSON ?= " + acceptJson); String method; boolean isPost; switch (requestMethod) { case REQUEST_METHOD_GET: method = "GET"; isPost = false; break; case REQUEST_METHOD_POST: method = "POST"; isPost = true; break; default: method = "GET"; isPost = false; break; } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); conn.setRequestProperty("Content-Type", JSON_UTF8_CONTENT_TYPE); if (isPost && acceptJson) { conn.setRequestProperty("Accept", JSON_CONTENT_TYPE); } conn.setRequestMethod(method); /* setDoOutput(true) equals setRequestMethod("POST") */ conn.setDoOutput(isPost); conn.setChunkedStreamingMode(0); // Starts the query conn.connect(); return conn; }
From source file:com.mnt.base.util.HttpUtil.java
public static String processPostRequest2Text(String url, Map<String, Object> parameters, Map<String, String> headerValue) { HttpURLConnection connection = null; try {//from w ww. jav a2 s .com connection = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { log.error("Error while process http get request.", e); } if (connection != null) { try { connection.setRequestMethod("POST"); connection.setDoOutput(true); } catch (ProtocolException e) { log.error("should not happen to get error while set the request method as GET.", e); } if (!CommonUtil.isEmpty(headerValue)) { for (String key : headerValue.keySet()) { connection.setRequestProperty(key, headerValue.get(key)); } } // need to specify the content type for post request connection.setRequestProperty("Content-Type", "application/json"); setTimeout(connection); String resultStr = null; try { connection.connect(); if (parameters != null) { String jsonParams = null; try { jsonParams = JSONTool.convertObjectToJson(parameters); } catch (Exception e) { log.error("error while process parameters to json string.", e); } if (jsonParams != null) { connection.getOutputStream().write(jsonParams.getBytes()); connection.getOutputStream().flush(); } } resultStr = readData(connection.getInputStream()); } catch (IOException e) { log.error("fail to connect to url: " + url, e); } finally { connection.disconnect(); } return resultStr; } return null; }
From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java
/** * Opens a POST connection./*from ww w . ja v a 2 s .c o m*/ * * @param url The URL to connect to. * * @return A POST connection to this URL. * @throws IOException If an exception occurred while contacting the server. */ static private HttpURLConnection getPOSTConnection(String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:crow.weibo.util.WeiboUtil.java
public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException { OutputStream os;/*from www. j ava 2 s . com*/ List<PostParameter> dataparams = new ArrayList<PostParameter>(); for (PostParameter key : params) { if (key.isFile()) { dataparams.add(key); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); ByteArrayBuffer buff = new ByteArrayBuffer(1000); for (PostParameter p : params) { byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8"); buff.append(arr, 0, arr.length); } String end = "--" + BOUNDARY + "--" + "\r\n"; byte[] endArr = end.getBytes(); buff.append(endArr, 0, endArr.length); conn.setRequestProperty("Content-Length", buff.length() + ""); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(buff.toByteArray()); buff.clear(); os.flush(); String response = ""; response = Util.inputStreamToString(conn.getInputStream()); return response; }
From source file:Main.java
@TargetApi(Build.VERSION_CODES.KITKAT) public static String net(String strUrl, Map<String, Object> params, String method) throws Exception { HttpURLConnection conn = null; BufferedReader reader = null; String rs = null;//from w w w. ja v a2 s .c om try { StringBuffer sb = new StringBuffer(); if (method == null || method.equals("GET")) { strUrl = strUrl + "?" + urlencode(params); } URL url = new URL(strUrl); conn = (HttpURLConnection) url.openConnection(); if (method == null || method.equals("GET")) { conn.setRequestMethod("GET"); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); } conn.setRequestProperty("User-agent", userAgent); conn.setUseCaches(false); conn.setConnectTimeout(DEF_CONN_TIMEOUT); conn.setReadTimeout(DEF_READ_TIMEOUT); conn.setInstanceFollowRedirects(false); conn.connect(); if (params != null && method.equals("POST")) { try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(urlencode(params)); } } InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET)); String strRead = null; while ((strRead = reader.readLine()) != null) { sb.append(strRead); } rs = sb.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } return rs; }