List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.konakart.actions.gateways.BaseGatewayAction.java
/** * Sends data to the payment gateway via a POST. Parameters are received from the PaymentDetails * object and the credit card parameters that have just been input by the customer are sent in a * separate list; the ccParmList. Any miscellaneous parameters can also be added to the * ccParmList if required. If postData is not null, then the data it contains is used instead of * the data from the PaymentDetails and ccParmList. * /*from w ww . ja v a 2 s .c o m*/ * @param postData * The data to be posted. Can be null. * @param pd * the PaymentDetails object * @param ccParmList * @return The response to the post * @throws IOException */ public String postData(StringBuffer postData, PaymentDetailsIf pd, List<NameValueIf> ccParmList) throws IOException { URL url = new URL(pd.getRequestUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); if (pd.getReferrer() != null && pd.getReferrer().length() > 1) { connection.setRequestProperty("Referer", pd.getReferrer()); } // This one is deprecated but we still need to call it customizeConnection(connection); // This is the one that should be used from v5.5.0.0 customizeConnection(connection, pd, ccParmList); PrintWriter out = new PrintWriter(connection.getOutputStream()); StringBuffer sb = (postData == null) ? getGatewayRequest(pd, ccParmList) : postData; if (log.isDebugEnabled()) { log.debug("Post URL = " + pd.getRequestUrl()); log.debug("Post string =\n" + RegExpUtils.maskCreditCard(sb.toString())); } // Send the message out.print(sb.toString()); out.close(); // Get back the response StringBuffer respSb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = in.readLine(); while (line != null) { respSb.append(line); line = in.readLine(); } in.close(); return respSb.toString(); }
From source file:com.facebook.android.FBUtil.java
/** * Connect to an HTTP URL and return the response as a string. * * 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/*ww w . j a v a2 s . c om*/ * @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; // Try to get filename key String filename = params.getString("filename"); // If found if (filename != null) { // Remove from params params.remove("filename"); } if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Facebook-FBUtil", 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)); } } // 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=\"" + ((filename) != null ? 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()); } return response; }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*from ww w . j a va2s . co m*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return ? */ public String uploadMedia(String msgType, String localFile, HttpServletRequest request) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + getAccessToken() + "&type=" + msgType; String local_url = this.getRealPath(request, localFile); // 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); // 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.google.samples.quickstart.signin.MainActivity.java
private String downloadUrl(String myurl, String tokenid) throws IOException { InputStream is = null;/* w w w .ja v a 2s. co m*/ // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); JSONObject cred = new JSONObject(); cred.put("tokenid", tokenid); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(cred.toString()); wr.flush(); //con.setRequestMethod("POST"); //conn.setRequestProperty("tokenid",tokenid); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } catch (JSONException e) { e.printStackTrace(); return null; } finally { if (is != null) { is.close(); } } }
From source file:com.huixueyun.tifenwang.api.net.HttpEngine.java
/** * ?connection/* w ww . j av a 2s. c om*/ * * @param paramUrl ?? * @return HttpURLConnection */ private HttpURLConnection getConnection(String paramUrl) { HttpURLConnection connection = null; // ?connection try { // ??URL URL url = new URL(SERVER_URL + paramUrl); // ?URL connection = (HttpURLConnection) url.openConnection(); // ? connection.setRequestMethod(REQUEST_MOTHOD); // ??POST?true connection.setDoInput(true); // ??POST? connection.setDoOutput(true); // ? connection.setUseCaches(false); // connection.setReadTimeout(TIME_OUT); connection.setConnectTimeout(TIME_OUT); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Response-Type", "json"); connection.setChunkedStreamingMode(0); } catch (IOException e) { e.printStackTrace(); } return connection; }
From source file:com.data.pack.Util.java
/** * Connect to an HTTP URL and return the response as a string. * // w ww. j a va 2 s .c o 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); } Util.logd("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)); } } // 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()); } return response; }
From source file:AIR.Common.Web.HttpWebHelper.java
public String getResponse(String urlString, String postRequestParams, String contentMimeType) throws Exception { try {//from w w w. ja va 2 s . co m URL url = new URL(urlString); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Content-Type", String.format("application/%s; charset=UTF-8", contentMimeType)); urlConn.setUseCaches(false); // the request will return a response urlConn.setDoInput(true); // set request method to POST urlConn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream()); writer.write(postRequestParams); writer.flush(); // reads response, store line by line in an array of Strings BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuffer bfr = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { bfr.append(line + "\n"); } reader.close(); writer.close(); urlConn.disconnect(); return bfr.toString(); } catch (Exception exp) { StringWriter strn = new StringWriter(); exp.printStackTrace(new PrintWriter(strn)); _logger.error(strn.toString()); exp.printStackTrace(); throw new Exception(exp); } }
From source file:TestHTTPSource.java
@Test public void testHttpsSourceNonHttpsClient() throws Exception { Type listType = new TypeToken<List<JSONEvent>>() { }.getType();/*w w w. jav a 2 s . c om*/ List<JSONEvent> events = Lists.newArrayList(); Random rand = new Random(); for (int i = 0; i < 10; i++) { Map<String, String> input = Maps.newHashMap(); for (int j = 0; j < 10; j++) { input.put(String.valueOf(i) + String.valueOf(j), String.valueOf(i)); } input.put("MsgNum", String.valueOf(i)); JSONEvent e = new JSONEvent(); e.setHeaders(input); e.setBody(String.valueOf(rand.nextGaussian()).getBytes("UTF-8")); events.add(e); } Gson gson = new Gson(); String json = gson.toJson(events, listType); HttpURLConnection httpURLConnection = null; try { URL url = new URL("http://0.0.0.0:" + sslPort); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.getOutputStream().write(json.getBytes()); httpURLConnection.getResponseCode(); Assert.fail("HTTP Client cannot connect to HTTPS source"); } catch (Exception exception) { Assert.assertTrue("Exception expected", true); } finally { httpURLConnection.disconnect(); } }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status getFeed(FeedUpdater feedUpdater) { Status s = Status.NEED_AUTH;// ww w. ja va 2 s .co m s.authMethod = AuthMethod.USER_PASS; if (loginID == null || loginSecretHashed == null) { if ((s = connect()) != Status.OK) { return s; } } HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(FEED_URL).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); final JSONObject req = getRequestObject(); final OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(req.toString().getBytes()); out.flush(); out.close(); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = SyncHelper.parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == HttpStatus.SC_OK) { parseFeed(feedUpdater, reply); return Status.OK; } } catch (final MalformedURLException e) { e.printStackTrace(); s.ex = e; } catch (final IOException e) { e.printStackTrace(); s.ex = e; } catch (final JSONException e) { e.printStackTrace(); s.ex = e; } s = Status.ERROR; if (conn != null) conn.disconnect(); return s; }
From source file:eu.codeplumbers.cosi.services.CosiCallService.java
public void sendChangesToCozy() { List<Call> unSyncedCalls = Call.getAllUnsynced(); int i = 0;/*from w w w . j a va2s .c om*/ for (Call call : unSyncedCalls) { URL urlO = null; try { JSONObject jsonObject = call.toJsonObject(); mBuilder.setProgress(unSyncedCalls.size(), i, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new CallSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_calls_send_changes))); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(syncUrl); requestMethod = "POST"; } else { urlO = new URL(syncUrl + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); long objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); call.setRemoteId(result); call.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } i++; } }