List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.drive.student.xutils.HttpUtils.java
/** * Server/*from w ww . j a v a 2s.c o m*/ * * @param urlStr * ? * @param serverFileName * ????? image.jpg * @param uploadFile * ? /sdcard/a.jpg */ public void uploadFile(String urlStr, String serverFileName, File uploadFile) { try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setChunkedStreamingMode(1024 * 1024); conn.setRequestMethod("POST"); conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;file=" + uploadFile.getName()); conn.setRequestProperty("filename", uploadFile.getName()); OutputStream out = new DataOutputStream(conn.getOutputStream()); DataInputStream in = new DataInputStream(new FileInputStream(uploadFile)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); out.flush(); out.close(); int response = conn.getResponseCode(); if (response == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } LogUtil.e("hxk", "upload file success-->>"); } else { LogUtil.e("hxk", "upload file fail-->> response = " + response); } } catch (Exception e) { e.printStackTrace(); LogUtil.e("hxk", "upload file fail-->>"); } }
From source file:com.example.ronald.tracle.MainActivity.java
private String downloadContent(String myurl) throws IOException { InputStream is = null;// w w w. ja v a 2 s. c o m int length = 500; //SPECIAL CASE IN THIS ACTIIVTY String SITA_HOST = "flifo-qa.api.aero"; // END OF SPECIAL PART try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("X-apiKey", SITA_KEY); conn.setRequestProperty("Host", SITA_HOST); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = convertInputStreamToString(is, length); return contentAsString; } finally { if (is != null) { is.close(); } } }
From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java
/** * This method uploads an image from the given uri. It does the uploading in * small chunks to make sure it doesn't over run the memory. * /*from w ww . j av a 2 s .c om*/ * @param uri * image location * @return map containing data from interaction */ private String readPictureDataAndUpload(final Uri uri) { Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)"); try { final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); final int totalFileLength = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); // Create custom progress notification mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress), System.currentTimeMillis()); // set as ongoing mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT; // set custom view to notification mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength); //empty intent for the notification final Intent progressIntent = new Intent(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0); mProgressNotification.contentIntent = contentIntent; // add notification to manager mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); final InputStream inputStream = getContentResolver().openInputStream(uri); final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((new Random()).nextLong()); final String boundary = "--" + boundaryString; final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json")) .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\""); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(CHUNK_SIZE); final OutputStream hrout = conn.getOutputStream(); final PrintStream hout = new PrintStream(hrout); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"key\""); hout.println("Content-Type: text/plain"); hout.println(); Random rng = new Random(); String key = API_KEYS[rng.nextInt(API_KEYS.length)]; hout.println(key); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"image\""); hout.println("Content-Transfer-Encoding: base64"); hout.println(); hout.flush(); { final Base64OutputStream bhout = new Base64OutputStream(hrout); final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES]; int read = 0; int totalRead = 0; long lastLogTime = 0; while (read >= 0) { read = inputStream.read(pictureData); if (read > 0) { bhout.write(pictureData, 0, read); totalRead += read; if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) { lastLogTime = System.currentTimeMillis(); Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength + " bytes (" + (100 * totalRead) / totalFileLength + "%)"); //make a final version of the total read to make the handler happy final int totalReadFinal = totalRead; mHandler.post(new Runnable() { public void run() { mProgressNotification.contentView = generateProgressNotificationView( totalReadFinal, totalFileLength); mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); } }); } bhout.flush(); hrout.flush(); } } Log.d(this.getClass().getName(), "Finishing upload..."); // This close is absolutely necessary, this tells the // Base64OutputStream to finish writing the last of the data // (and including the padding). Without this line, it will miss // the last 4 chars in the output, missing up to 3 bytes in the // final output. bhout.close(); Log.d(this.getClass().getName(), "Upload complete..."); mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead, false); mNotificationManager.cancelAll(); } hout.println(boundary); hout.flush(); hrout.close(); inputStream.close(); Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder rData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { rData.append(line).append('\n'); } return rData.toString(); } catch (final IOException e) { Log.e(this.getClass().getName(), "Upload failed", e); } return null; }
From source file:com.geodan.ngr.serviceintegration.CSWTransformer.java
/** * POSTs the xml request to the given url and returns a String representation of the response. * * @param xml_request the request contains the search criteria * @param url the url to POST the request to * @return returns a String representation of the response * @throws IOException in case of exception *//* w w w. ja v a 2 s . c om*/ private String post(String xml_request, String url) throws IOException { // Create an URL object log.debug("creating request to URL: " + url); URL csUrl = new URL(url); // Create an HttpURLConnection and use the URL object to POST the request HttpURLConnection csUrlConn = (HttpURLConnection) csUrl.openConnection(); csUrlConn.setDoOutput(true); csUrlConn.setDoInput(true); csUrlConn.setRequestMethod("POST"); csUrlConn.setRequestProperty("Content-Type", "text/xml"); // Create a OutputStream to actually send the request and close the streams OutputStream out = csUrlConn.getOutputStream(); OutputStreamWriter wout = new OutputStreamWriter(out, "UTF-8"); wout.write(xml_request); wout.flush(); out.close(); // Get a InputStream and parse it in the parse method InputStream is = csUrlConn.getInputStream(); String response = ""; if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } finally { is.close(); } response = sb.toString(); } // Close Streams and connections out.close(); csUrlConn.disconnect(); if (response != null && response.length() > 0) { log.debug("GetRecords response:\n" + response); } else { log.debug("GetRecords response empty"); } // Returns response return response; }
From source file:com.asto.move.util.qcloud.pic.PicCloud.java
/** * Download ??//from www .j a va2 s . co m * * @param url * @param fileName ? * @return ?0? */ public int Download(String url, String fileName) { if (fileName == null || "".equals(fileName)) { return SetError(-1, "file name is empty."); } String rsp = ""; try { URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setRequestMethod("GET"); connection.setRequestProperty("Host", "web.image.myqcloud.com"); connection.setRequestProperty("user-agent", "qcloud-java-sdk"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); InputStream in = new DataInputStream(connection.getInputStream()); File file = new File(fileName); String path = ""; if (!file.exists()) { path = fileName.substring(0, fileName.lastIndexOf("/")); File catalogFile = new File(path); catalogFile.mkdirs(); } DataOutputStream ops = new DataOutputStream(new FileOutputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) > 0) { ops.write(bufferOut, 0, bytes); } ops.close(); in.close(); } catch (Exception e) { return SetError(-1, "url exception, e=" + e.toString()); } return SetError(0, "success"); }
From source file:com.asto.move.util.qcloud.pic.PicCloud.java
/** * Stat ?/*from w w w. jav a2s . co m*/ * * @param info ? * @return ?0? */ public int Stat(String fileid, PicInfo info) { String req_url = GetUrl(fileid); String rsp = ""; try { URL realUrl = new URL(req_url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setRequestMethod("GET"); connection.setRequestProperty("Host", "web.image.myqcloud.com"); connection.setRequestProperty("user-agent", "qcloud-java-sdk"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); // read rsp rsp = GetResponse(connection); } catch (Exception e) { return SetError(-1, "url exception, e=" + e.toString()); } try { JSONObject jsonObject = new JSONObject(rsp); int code = jsonObject.getInt("code"); String msg = jsonObject.getString("message"); if (0 != code) { return SetError(code, msg); } info.url = jsonObject.getJSONObject("data").getString("file_url"); info.fileid = jsonObject.getJSONObject("data").getString("file_fileid"); info.upload_time = jsonObject.getJSONObject("data").getInt("file_upload_time"); info.size = jsonObject.getJSONObject("data").getInt("file_size"); info.md5 = jsonObject.getJSONObject("data").getString("file_md5"); info.width = jsonObject.getJSONObject("data").getInt("photo_width"); info.height = jsonObject.getJSONObject("data").getInt("photo_height"); } catch (JSONException e) { return SetError(-1, "json exception, e=" + e.toString()); } return SetError(0, "success"); }
From source file:com.maass.android.imgur_uploader.ImgurUpload.java
/** * This method uploads an image from the given uri. It does the uploading in * small chunks to make sure it doesn't over run the memory. * //from w ww. ja v a2s. c om * @param uri * image location * @return map containing data from interaction */ private String readPictureDataAndUpload(final Uri uri) { Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)"); try { final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); final int totalFileLength = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); // Create custom progress notification mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress), System.currentTimeMillis()); // set as ongoing mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT; // set custom view to notification mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength); //empty intent for the notification final Intent progressIntent = new Intent(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0); mProgressNotification.contentIntent = contentIntent; // add notification to manager mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); final InputStream inputStream = getContentResolver().openInputStream(uri); final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((new Random()).nextLong()); final String boundary = "--" + boundaryString; final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json")) .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\""); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(CHUNK_SIZE); final OutputStream hrout = conn.getOutputStream(); final PrintStream hout = new PrintStream(hrout); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"key\""); hout.println("Content-Type: text/plain"); hout.println(); hout.println(API_KEY); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"image\""); hout.println("Content-Transfer-Encoding: base64"); hout.println(); hout.flush(); { final Base64OutputStream bhout = new Base64OutputStream(hrout); final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES]; int read = 0; int totalRead = 0; long lastLogTime = 0; while (read >= 0) { read = inputStream.read(pictureData); if (read > 0) { bhout.write(pictureData, 0, read); totalRead += read; if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) { lastLogTime = System.currentTimeMillis(); Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength + " bytes (" + (100 * totalRead) / totalFileLength + "%)"); //make a final version of the total read to make the handler happy final int totalReadFinal = totalRead; mHandler.post(new Runnable() { public void run() { mProgressNotification.contentView = generateProgressNotificationView( totalReadFinal, totalFileLength); mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); } }); } bhout.flush(); hrout.flush(); } } Log.d(this.getClass().getName(), "Finishing upload..."); // This close is absolutely necessary, this tells the // Base64OutputStream to finish writing the last of the data // (and including the padding). Without this line, it will miss // the last 4 chars in the output, missing up to 3 bytes in the // final output. bhout.close(); Log.d(this.getClass().getName(), "Upload complete..."); mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead, false); } hout.println(boundary); hout.flush(); hrout.close(); inputStream.close(); Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder rData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { rData.append(line).append('\n'); } return rData.toString(); } catch (final IOException e) { Log.e(this.getClass().getName(), "Upload failed", e); } return null; }
From source file:moodle.android.moodle.helpers.MoodleWebService.java
private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters, int xslRawId) { JSONObject jsonobj = null;//from www.jav a2 s . com try { HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection(); //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection(); con.setConnectTimeout(30000); con.setReadTimeout(30000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); con.setDoOutput(true); con.setUseCaches(false); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); Log.d("URLParameters: ", urlParameters.toString()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = con.getInputStream(); Source xmlSource = new StreamSource(is); Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String jsonstr = writer.toString(); jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", ""); jsonstr = jsonstr.replace("</p></div>", ""); jsonstr = jsonstr.replace("<p>", ""); jsonstr = jsonstr.replace("</p>", ""); Log.d("TransformObject: ", jsonstr); jsonobj = new JSONObject(jsonstr); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonobj; }
From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java
public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData) throws Throwable { HttpURLConnection connection = null; InputStream is = null;/*from w ww . j ava 2 s . com*/ int statusCode; if (DUMP_PAYLOAD) { log.debug("Send request to {}", remoteServiceURL); log.debug("Request payload: {}", requestData); } // Send request CookieHandler oldCookieHandler = CookieHandler.getDefault(); try { CookieHandler.setDefault(cookieManager); URL url = new URL(remoteServiceURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName); connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL); connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length); CookieStore store = cookieManager.getCookieStore(); String cookiesStr = ""; for (HttpCookie cookie : store.getCookies()) { if (!"".equals(cookiesStr)) cookiesStr += "; "; cookiesStr += cookie.getName() + "=" + cookie.getValue(); } connection.setRequestProperty("Cookie", cookiesStr); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestData); writer.flush(); writer.close(); } catch (IOException e) { throw new InvocationException("IOException while sending RPC request", e); } finally { CookieHandler.setDefault(oldCookieHandler); } // Receive and process response try { is = connection.getInputStream(); statusCode = connection.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { baos.write(buffer, 0, len); } String encodedResponse = baos.toString("UTF8"); if (DUMP_PAYLOAD) { log.debug("Response code: {}", statusCode); log.debug("Response payload: {}", encodedResponse); } // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse); if (statusCode != HttpURLConnection.HTTP_OK) { throw new StatusCodeException(statusCode, encodedResponse); } else if (encodedResponse == null) { // This can happen if the XHR is interrupted by the server dying throw new InvocationException("No response payload"); } else if (isReturnValue(encodedResponse)) { encodedResponse = encodedResponse.substring(4); return responseReader.read(createStreamReader(encodedResponse)); } else if (isThrownException(encodedResponse)) { encodedResponse = encodedResponse.substring(4); Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject(); throw throwable; } else { throw new InvocationException("Unknown response " + encodedResponse); } } catch (IOException e) { log.error("error response: {}", IOUtils.toString(connection.getErrorStream())); throw new InvocationException("IOException while receiving RPC response", e); } catch (SerializationException e) { throw new InvocationException("Error while deserialization response", e); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (connection != null) { // connection.disconnect(); } } }
From source file:com.wareninja.android.opensource.oauth2login.common.Utils.java
/** * Connect to an HTTP URL and return the response as a string. * //from w w w . j a v a 2s. co m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { /* if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } */ // YG: added this to avoid fups byte[] byteArr = null; try { byteArr = (byte[]) params.get(key); } catch (Exception ex1) { } if (byteArr != null) dataparams.putByteArray(key, byteArr); } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " response: " + response); return response; }