List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:de.wikilab.android.friendica01.TwAjax.java
private void runFileUpload() throws IOException { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594"; Log.i("Andfrnd/TwAjax", "URL=" + getURL()); URL url = new URL(getURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true);/*w w w. j a v a2s . c om*/ connection.setDoOutput(true); connection.setUseCaches(false); // Enable POST method connection.setRequestMethod("POST"); //generate auth header if user/pass are provided to this class if (this.myHttpAuthUser != null) { connection.setRequestProperty("Authorization", "Basic " + Base64 .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP)); } //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--"); connection.setRequestProperty("Host", url.getHost()); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); for (NameValuePair nvp : myPostData) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd); outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd); } for (PostFile pf : myPostFiles) { pf.writeToStream(outputStream, boundary); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) myHttpStatus = connection.getResponseCode(); outputStream.flush(); outputStream.close(); if (myHttpStatus < 400) { myResult = convertStreamToString(connection.getInputStream()); } else { myResult = convertStreamToString(connection.getErrorStream()); } success = true; }
From source file:org.c99.wear_imessage.RemoteInputService.java
@Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_REPLY.equals(action)) { JSONObject conversations = null, conversation = null; try { conversations = new JSONObject( getSharedPreferences("data", 0).getString("conversations", "{}")); } catch (JSONException e) { conversations = new JSONObject(); }/*from w w w . ja v a 2 s .c o m*/ try { String key = intent.getStringExtra("service") + ":" + intent.getStringExtra("handle"); if (conversations.has(key)) { conversation = conversations.getJSONObject(key); } else { conversation = new JSONObject(); conversations.put(key, conversation); long time = new Date().getTime(); String tmpStr = String.valueOf(time); String last4Str = tmpStr.substring(tmpStr.length() - 5); conversation.put("notification_id", Integer.valueOf(last4Str)); conversation.put("msgs", new JSONArray()); } } catch (JSONException e) { e.printStackTrace(); } Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput != null || intent.hasExtra("reply")) { String reply = remoteInput != null ? remoteInput.getCharSequence("extra_reply").toString() : intent.getStringExtra("reply"); if (intent.hasExtra(Intent.EXTRA_STREAM)) { NotificationCompat.Builder notification = new NotificationCompat.Builder(this) .setContentTitle("Uploading File").setProgress(0, 0, true).setLocalOnly(true) .setOngoing(true).setSmallIcon(android.R.drawable.stat_sys_upload); NotificationManagerCompat.from(this).notify(1337, notification.build()); InputStream fileIn = null; InputStream responseIn = null; HttpURLConnection http = null; try { String filename = ""; int total = 0; String type = getContentResolver() .getType((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)); if (type == null || type.length() == 0) type = "application/octet-stream"; fileIn = getContentResolver() .openInputStream((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM)); Cursor c = getContentResolver().query( (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM), new String[] { OpenableColumns.SIZE, OpenableColumns.DISPLAY_NAME }, null, null, null); if (c != null && c.moveToFirst()) { total = c.getInt(0); filename = c.getString(1); c.close(); } else { total = fileIn.available(); } String boundary = UUID.randomUUID().toString(); http = (HttpURLConnection) new URL( "http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/upload") .openConnection(); http.setReadTimeout(60000); http.setConnectTimeout(60000); http.setDoOutput(true); http.setFixedLengthStreamingMode(total + (boundary.length() * 5) + filename.length() + type.length() + intent.getStringExtra("handle").length() + intent.getStringExtra("service").length() + reply.length() + 251); http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = http.getOutputStream(); out.write(("--" + boundary + "\r\n").getBytes()); out.write(("Content-Disposition: form-data; name=\"handle\"\r\n\r\n").getBytes()); out.write((intent.getStringExtra("handle") + "\r\n").getBytes()); out.write(("--" + boundary + "\r\n").getBytes()); out.write(("Content-Disposition: form-data; name=\"service\"\r\n\r\n").getBytes()); out.write((intent.getStringExtra("service") + "\r\n").getBytes()); out.write(("--" + boundary + "\r\n").getBytes()); out.write(("Content-Disposition: form-data; name=\"msg\"\r\n\r\n").getBytes()); out.write((reply + "\r\n").getBytes()); out.write(("--" + boundary + "\r\n").getBytes()); out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n").getBytes()); out.write(("Content-Type: " + type + "\r\n\r\n").getBytes()); byte[] buffer = new byte[8192]; int count = 0; int n = 0; while (-1 != (n = fileIn.read(buffer))) { out.write(buffer, 0, n); count += n; float progress = (float) count / (float) total; if (progress < 1.0f) notification.setProgress(1000, (int) (progress * 1000), false); else notification.setProgress(0, 0, true); NotificationManagerCompat.from(this).notify(1337, notification.build()); } out.write(("\r\n--" + boundary + "--\r\n").getBytes()); out.flush(); out.close(); if (http.getResponseCode() == HttpURLConnection.HTTP_OK) { responseIn = http.getInputStream(); StringBuilder sb = new StringBuilder(); Scanner scanner = new Scanner(responseIn).useDelimiter("\\A"); while (scanner.hasNext()) { sb.append(scanner.next()); } android.util.Log.i("iMessage", "Upload result: " + sb.toString()); try { if (conversation != null) { JSONArray msgs = conversation.getJSONArray("msgs"); JSONObject m = new JSONObject(); m.put("msg", filename); m.put("service", intent.getStringExtra("service")); m.put("handle", intent.getStringExtra("handle")); m.put("type", "sent_file"); msgs.put(m); while (msgs.length() > 10) { msgs.remove(0); } GCMIntentService.notify(getApplicationContext(), intent.getIntExtra("notification_id", 0), msgs, intent, true); } } catch (Exception e) { e.printStackTrace(); } } else { responseIn = http.getErrorStream(); StringBuilder sb = new StringBuilder(); Scanner scanner = new Scanner(responseIn).useDelimiter("\\A"); while (scanner.hasNext()) { sb.append(scanner.next()); } android.util.Log.e("iMessage", "Upload failed: " + sb.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (responseIn != null) responseIn.close(); } catch (Exception ignore) { } try { if (http != null) http.disconnect(); } catch (Exception ignore) { } try { fileIn.close(); } catch (Exception ignore) { } } NotificationManagerCompat.from(this).cancel(1337); } else if (reply.length() > 0) { URL url = null; try { url = new URL("http://" + getSharedPreferences("prefs", 0).getString("host", "") + "/send?service=" + intent.getStringExtra("service") + "&handle=" + intent.getStringExtra("handle") + "&msg=" + URLEncoder.encode(reply, "UTF-8")); } catch (Exception e) { e.printStackTrace(); return; } HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); } catch (IOException e) { e.printStackTrace(); return; } conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setUseCaches(false); BufferedReader reader = null; try { if (conn.getInputStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512); } } catch (IOException e) { if (conn.getErrorStream() != null) { reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512); } } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } conn.disconnect(); try { if (conversation != null) { JSONArray msgs = conversation.getJSONArray("msgs"); JSONObject m = new JSONObject(); m.put("msg", reply); m.put("service", intent.getStringExtra("service")); m.put("handle", intent.getStringExtra("handle")); m.put("type", "sent"); msgs.put(m); while (msgs.length() > 10) { msgs.remove(0); } GCMIntentService.notify(getApplicationContext(), intent.getIntExtra("notification_id", 0), msgs, intent, true); } } catch (Exception e) { e.printStackTrace(); } } SharedPreferences.Editor e = getSharedPreferences("data", 0).edit(); e.putString("conversations", conversations.toString()); e.apply(); } } } }
From source file:RhodesService.java
public static boolean pingHost(String host) { HttpURLConnection conn = null; boolean hostExists = false; try {// w w w . j av a 2 s .co m URL url = new URL(host); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setAllowUserInteraction(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); hostExists = (conn.getContentLength() > 0); if (hostExists) Logger.I(TAG, "PING network SUCCEEDED."); else Logger.E(TAG, "PING network FAILED."); } catch (Exception e) { Logger.E(TAG, e); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { Logger.E(TAG, e); } } } return hostExists; }
From source file:com.curso.listadapter.net.RESTClient.java
/** * upload multipart/* ww w. ja v a2 s.c o m*/ * this method receive the file to be uploaded * */ @SuppressWarnings("deprecation") public String uploadMultiPart(Map<String, File> files) throws Exception { disableSSLCertificateChecking(); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; try { URL endpoint = new URL(url); conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); String post = ""; //WRITE ALL THE PARAMS for (NameValuePair p : params) post += writeMultipartParam(p); dos.flush(); //END WRITE ALL THE PARAMS //BEGIN THE UPLOAD ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>(); for (Entry<String, File> entry : files.entrySet()) { post += lineEnd; post += twoHyphens + boundary + lineEnd; String NameParamImage = entry.getKey(); File file = entry.getValue(); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; FileInputStream fileInputStream = new FileInputStream(file); post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName() + "\"" + lineEnd; String mimetype = getMimeType(file.getName()); post += "Content-Type: " + mimetype + lineEnd; post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd; dos.write(post.toString().getBytes("UTF-8")); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); inputStreams.add(fileInputStream); } Log.d("Test", post); dos.flush(); post = ""; } //END THE UPLOAD dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens); // for(FileInputStream inputStream: inputStreams){ // inputStream.close(); // } dos.flush(); dos.close(); conn.connect(); Log.d("upload", "finish flush:" + conn.getResponseCode()); } catch (MalformedURLException ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("Debug", "error: " + ioe.getMessage(), ioe); } try { String response_data = ""; inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { response_data += str; } inStream.close(); return response_data; } catch (IOException ioex) { Log.e("Debug", "error: " + ioex.getMessage(), ioex); } return null; }
From source file:com.erdao.PhotSpotCloud.PhotSpotCloudServlet.java
/** * Open specific url and set to StringBuilder * @param url//ww w . j av a 2 s . com * @return StringBuilder */ private StringBuilder openFeed(String requestUrl) { openfeedSuccess_ = false; HttpURLConnection connection; StringBuilder strbuilder = null; BufferedReader reader; URL url = null; try { url = new URL(requestUrl); } catch (MalformedURLException e) { return null; } for (int i = 0; i < MAX_RETRY; i++) { try { connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setRequestProperty("Content-type", "text/plain"); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); reader = new BufferedReader(isr, IO_BUFFER_SIZE); strbuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { strbuilder.append(line + "\n"); } is.close(); } } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } if (strbuilder != null) { openfeedSuccess_ = true; break; } } return strbuilder; }
From source file:api.APICall.java
public String executePost(String targetURL, String urlParameters) { URL url;/*from ww w .j a v a 2s . c o m*/ HttpURLConnection connection = null; try { // Create connection url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (SocketException se) { se.printStackTrace(); System.out.println("Server is down."); return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java
public Boolean upload_v2() { this.downloader.login(); String page = this.downloader.getUrlData(this.URL); String viewstate = ""; Pattern p = Pattern//w ww .j av a2 s .c o m .compile("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"([^\"]+)\" />"); Matcher m = p.matcher(page); m.find(); viewstate = m.group(1); //System.out.println("viewstate=" + viewstate); // got viewstate InputStream fn_is = null; String raw_upload_data = ""; try { fn_is = new ByteArrayInputStream( ("GC2BNHP,2010-11-07T14:00Z,Write note,\"bla bla\"").getBytes("UTF-8")); raw_upload_data = "GC2BNHP,2010-11-07T20:50Z,Write note,\"bla bla\"".getBytes("UTF-8").toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String cookies_string = this.downloader.getCookies(); ArrayList<InputStream> files = new ArrayList(); files.add(fn_is); Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht.put("__VIEWSTATE", viewstate); HttpData data = HttpRequest.post(this.URL, ht, files, cookies_string); //System.out.println(data.content); String boundary = "----------ThIs_Is_tHe_bouNdaRY_$"; String crlf = "\r\n"; URL url = null; try { url = new URL(this.URL); } catch (MalformedURLException e2) { e2.printStackTrace(); } HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException e2) { e2.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); try { con.setRequestMethod("POST"); } catch (java.net.ProtocolException e) { e.printStackTrace(); } con.setRequestProperty("Cookie", cookies_string); //System.out.println("Cookie: " + cookies_string[0] + "=" + cookies_string[1]); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"); con.setRequestProperty("Pragma", "no-cache"); //con.setRequestProperty("Connection", "Keep-Alive"); String content_type = String.format("multipart/form-data; boundary=%s", boundary); con.setRequestProperty("Content-Type", content_type); DataOutputStream dos = null; try { dos = new DataOutputStream(con.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } String raw_data = ""; // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$btnUpload") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "Upload Field Note" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$chkSuppressDate") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "__VIEWSTATE") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + viewstate + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", "ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt") + crlf; raw_data = raw_data + String.format("Content-Type: %s", "text/plain") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + raw_upload_data + crlf; // // raw_data = raw_data + "--" + boundary + "--" + crlf; raw_data = raw_data + crlf; try { this.SendPost(this.URL, raw_data, cookies_string); } catch (IOException e1) { e1.printStackTrace(); } //System.out.println(raw_data); try { dos.writeBytes(raw_data); //dos.writeChars(raw_data); dos.flush(); } catch (IOException e) { e.printStackTrace(); } HttpData ret2 = new HttpData(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(con.getInputStream()), HTMLDownloader.large_buffer_size); String line; while ((line = rd.readLine()) != null) { ret2.content += line + "\r\n"; } } catch (IOException e) { e.printStackTrace(); } //get headers Map<String, List<String>> headers = con.getHeaderFields(); Set<Entry<String, List<String>>> hKeys = headers.entrySet(); for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) { Entry<String, List<String>> m99 = i.next(); //System.out.println("HEADER_KEY" + m99.getKey() + "=" + m99.getValue()); ret2.headers.put(m99.getKey(), m99.getValue().toString()); if (m99.getKey().equals("set-cookie")) ret2.cookies.put(m99.getKey(), m99.getValue().toString()); } try { dos.close(); rd.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println(ret2.content); //System.out.println("FFFFFFFFFFFFFFFFFFFFFFFFFFFF"); ClientHttpRequest client_req; try { client_req = new ClientHttpRequest(this.URL); String[] cookies_string2 = this.downloader.getCookies2(); for (int jk = 0; jk < cookies_string2.length; jk++) { System.out.println(cookies_string2[jk * 2] + "=" + cookies_string2[(jk * 2) + 1]); client_req.setCookie(cookies_string2[jk * 2], cookies_string2[(jk * 2) + 1]); } client_req.setParameter("ctl00$ContentBody$btnUpload", "Upload Field Note"); client_req.setParameter("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt", fn_is); InputStream response = client_req.post(); //System.out.println(this.convertStreamToString(response)); } catch (IOException e) { e.printStackTrace(); } //ArrayList<InputStream> files = new ArrayList(); files.clear(); files.add(fn_is); Hashtable<String, String> ht2 = new Hashtable<String, String>(); ht2.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht2.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht2.put("__VIEWSTATE", viewstate); HttpData data3 = HttpRequest.post(this.URL, ht2, files, cookies_string); //System.out.println(data3.content); // String the_page2 = this.downloader.get_reader_mpf(this.URL, raw_data, null, true, boundary); //System.out.println("page2=\n" + the_page2); Boolean ret = false; return ret; }
From source file:org.apache.openmeetings.web.pages.auth.SignInPage.java
private AuthInfo getToken(String code, OAuthServer server) throws IOException { String requestTokenBaseUrl = server.getRequestTokenUrl(); // build url params to request auth token String requestTokenParams = server.getRequestTokenAttributes(); requestTokenParams = prepareUrlParams(requestTokenParams, server.getClientId(), server.getClientSecret(), null, getRedirectUri(server, this), code); // request auth token HttpURLConnection urlConnection = (HttpURLConnection) new URL(requestTokenBaseUrl).openConnection(); prepareConnection(urlConnection);/* w w w. j ava 2s. co m*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("charset", StandardCharsets.UTF_8.name()); urlConnection.setRequestProperty("Content-Length", String.valueOf(requestTokenParams.length())); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); DataOutputStream paramsOutputStream = new DataOutputStream(urlConnection.getOutputStream()); paramsOutputStream.writeBytes(requestTokenParams); paramsOutputStream.flush(); String sourceResponse = IOUtils.toString(urlConnection.getInputStream(), StandardCharsets.UTF_8); // parse json result AuthInfo result = new AuthInfo(); try { JSONObject jsonResult = new JSONObject(sourceResponse.toString()); if (jsonResult.has("access_token")) { result.accessToken = jsonResult.getString("access_token"); } if (jsonResult.has("refresh_token")) { result.refreshToken = jsonResult.getString("refresh_token"); } if (jsonResult.has("token_type")) { result.tokenType = jsonResult.getString("token_type"); } if (jsonResult.has("expires_in")) { result.expiresIn = jsonResult.getLong("expires_in"); } } catch (JSONException e) { // try to parse as canonical Map<String, String> parsedMap = parseCanonicalResponse(sourceResponse.toString()); result.accessToken = parsedMap.get("access_token"); result.refreshToken = parsedMap.get("refresh_token"); result.tokenType = parsedMap.get("token_type"); try { result.expiresIn = Long.valueOf(parsedMap.get("expires_in")); } catch (NumberFormatException nfe) { } } // access token must be specified if (result.accessToken == null) { log.error("Response doesn't contain access_token field:\n" + sourceResponse.toString()); return null; } return result; }
From source file:com.mycompany.grupo6ti.GenericResource.java
@POST @Produces("application/json") @Path("/cancelarFactura/{id}/{motivo}") public String anularFactura(@PathParam("id") String id, @PathParam("motivo") String motivo) { try {//from w w w. j ava2 s . c o m URL url = new URL("http://localhost:85/cancel/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is; conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(true); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); String idJson = "{\n" + " \"id\": \"" + id + "\",\n" + " \"motivo\": \"" + motivo + "\"\n" + "}"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(idJson); out.flush(); out.close(); if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { is = conn.getInputStream(); } String result2 = ""; BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { result2 += line; } rd.close(); return result2; } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ("[\"Test\", \"Funcionando Bien\"]"); }
From source file:com.mycompany.grupo6ti.GenericResource.java
@PUT @Produces("application/json") @Path("emitirFactura/{id_oC}") public String emitirFactura(@PathParam("id_oC") String id_oC) { try {/*from w w w . ja v a 2 s .c o m*/ URL url = new URL("http://localhost:85/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is; conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "application/json"); conn.setUseCaches(true); conn.setRequestMethod("PUT"); conn.setDoOutput(true); conn.setDoInput(true); String idJson = "{\n" + " \"oc\": \"" + id_oC + "\"\n" + "}"; //String idJson2 = "[\"Test\", \"Funcionando Bien\"]"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(idJson); out.flush(); out.close(); if (conn.getResponseCode() >= 400) { is = conn.getErrorStream(); } else { is = conn.getInputStream(); } String result2 = ""; BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while ((line = rd.readLine()) != null) { result2 += line; } rd.close(); return result2; } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ("[\"Test\", \"Funcionando Bien\"]"); }