List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
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 ww w.j ava2 s . co 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.hippo.httpclient.JsonPoster.java
@Override public void onBeforeConnect(HttpURLConnection conn) throws Exception { super.onBeforeConnect(conn); conn.setDoOutput(true); conn.setDoInput(true);/*from www .j ava2s . c o m*/ conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); }
From source file:acclaim.Acclaim.java
public String doHTTPPostRequest(String url) throws Exception { String rawData = "id=10"; String type = "application/x-www-form-urlencoded"; String encodedData = URLEncoder.encode(rawData); URL u = new URL("http://www.example.com/page.php"); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length())); OutputStream os = conn.getOutputStream(); os.write(encodedData.getBytes());/*from w w w . j av a 2 s. co m*/ return null; }
From source file:com.flozano.socialauth.util.HttpUtil.java
/** * Makes HTTP request using java.net.HTTPURLConnection and optional settings * for the connection/*from w w w .jav a2 s .c o m*/ * * @param urlStr * the URL String * @param requestMethod * Method type * @param body * Body to pass in request. * @param header * Header parameters * @param connectionSettings * The connection settings to apply * @return Response Object * @throws SocialAuthException */ public static Response doHttpRequest(final String urlStr, final String requestMethod, final String body, final Map<String, String> header, Optional<ConnectionSettings> connectionSettings) throws SocialAuthException { HttpURLConnection conn; try { URL url = new URL(urlStr); if (proxyObj != null) { conn = (HttpURLConnection) url.openConnection(proxyObj); } else { conn = (HttpURLConnection) url.openConnection(); } connectionSettings.ifPresent(settings -> settings.apply(conn)); if (MethodType.POST.toString().equalsIgnoreCase(requestMethod) || MethodType.PUT.toString().equalsIgnoreCase(requestMethod)) { conn.setDoOutput(true); } conn.setDoInput(true); conn.setInstanceFollowRedirects(true); if (timeoutValue > 0) { LOG.debug("Setting connection timeout : " + timeoutValue); conn.setConnectTimeout(timeoutValue); } if (requestMethod != null) { conn.setRequestMethod(requestMethod); } if (header != null) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } // If use POST or PUT must use this OutputStream os = null; if (body != null) { if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod) && !MethodType.DELETE.toString().equals(requestMethod)) { os = conn.getOutputStream(); DataOutputStream out = new DataOutputStream(os); out.write(body.getBytes("UTF-8")); out.flush(); } } conn.connect(); } catch (Exception e) { throw new SocialAuthException(e); } return new Response(conn); }
From source file:com.gson.util.HttpKit.java
/** * ?http?// ww w. j a v a 2 s .co m * @param url * @param method * @param headers * @return * @throws IOException */ private static HttpURLConnection initHttp(String url, String method, Map<String, String> headers) throws IOException { URL _url = new URL(url); HttpURLConnection http = (HttpURLConnection) _url.openConnection(); // http.setConnectTimeout(25000); // ? --?? http.setReadTimeout(25000); http.setRequestMethod(method); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (null != headers && !headers.isEmpty()) { for (Entry<String, String> entry : headers.entrySet()) { http.setRequestProperty(entry.getKey(), entry.getValue()); } } http.setDoOutput(true); http.setDoInput(true); http.connect(); return http; }
From source file:com.vmanolache.mqttpolling.Polling.java
private void sendPost() throws UnsupportedEncodingException, JSONException { try {/*from w ww .ja va 2 s. co m*/ String url = "http://localhost:8080/notifications"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("POST"); /** * POSTing * */ OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery()); // should be fine if my getQuery is encoded right yes? writer.flush(); writer.close(); os.close(); connection.connect(); int status = connection.getResponseCode(); System.out.println(status); } catch (IOException ex) { Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.collection.JsonObjectRequest.java
/** * Helper method to make an HTTP request. * @param urlConnection The HTTP connection. *///from w ww. ja va2 s . co m public void writeToUrlConnection(HttpURLConnection urlConnection) throws IOException { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestMethod("POST"); OutputStream os = urlConnection.getOutputStream(); os.write(mJsonObject.toString().getBytes("UTF-8")); os.close(); }
From source file:org.csware.ee.utils.Tools.java
public static String reqByPost(String path) { String info = ""; try {//from www. j a v a 2 s . c o m // URL URL url = new URL(path); // HttpURLConnection HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // ?Input?output?Cache urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); /** ?method=post */ urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Charset", "utf-8"); InputStream in = urlConn.getInputStream(); try { byte[] buffer = new byte[65536]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int readLength = in.read(buffer); long totalLength = 0; while (readLength >= 0) { bos.write(buffer, 0, readLength); totalLength = totalLength + readLength; readLength = in.read(buffer); } info = bos.toString(); } finally { if (in != null) try { in.close(); } catch (Exception e) { e.printStackTrace(); } } // urlConn.setConnectTimeout(5 * 1000); // urlConn.connect(); } catch (Exception ex) { ex.printStackTrace(); return null; } return info.replaceAll("\r\n", " "); }
From source file:com.selene.volley.stack.HurlStack.java
@SuppressWarnings("deprecation") private static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/* w w w . j a va2 s . c o m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: connection.setRequestMethod("PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:javaapplication1.Prog.java
public void transferStuff(String obj, String user) throws MalformedURLException, IOException { URL object = new URL("http://localhost:8080/bankserver/users/" + user); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestMethod("PUT"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(obj);/* w ww . j ava 2 s.com*/ wr.flush(); wr.close(); con.getInputStream(); }