List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:com.android.volley.toolbox.AuthenticationChallengesProofHurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from ww w . j a v a 2 s .co m*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); /************************/ /****** WORKAROUND ******/ int responseCode; try { // Will throw IOException if server responds with 401. responseCode = connection.getResponseCode(); } catch (IOException e) { // You can get the response code after an exception if you call .getResponseCode() // a second time on the connection object. This is because the first time you // call .getResponseCode() an internal state is set that enables .getResponseCode() // to return without throwing an exception. responseCode = connection.getResponseCode(); } /************************/ if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w w w . j a va 2s. c om*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:prototypes.ws.proxy.soap.proxy.ProxyServlet.java
/** * Recept all request./*from w w w . jav a2 s . co m*/ * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpURLConnection httpConn = null; LOGGER.debug("doRequest"); BackendExchange backendExchange = RequestContext.getBackendExchange(request); LOGGER.trace("BackendExchange Hashcode : {}", Integer.toHexString(backendExchange.hashCode())); try { URL targetUrl = Requests.resolveTargetUrl(request, backendExchange.getUri()); httpConn = prepareBackendConnection(targetUrl, request, backendExchange.getRequestHeaders()); // save final state of request headers backendExchange.setRequestHeaders(httpConn.getRequestProperties()); // Send request byte[] body = backendExchange.getRequestBody(); backendExchange.start(); boolean gzipped = false; try { if (body.length > 0) { httpConn.getOutputStream().write(body); } else { LOGGER.warn("Body Empty"); } gzipped = "gzip".equals(httpConn.getContentEncoding()); // Get response. If response is gzipped, uncompress it backendExchange.setResponseBody(Streams.getBytes(httpConn.getInputStream(), gzipped)); } catch (java.net.SocketTimeoutException ex) { throw new IOException("Time out : " + ex.getMessage(), ex); } catch (IOException ex) { LOGGER.warn("Failed to read target response body {}", ex); backendExchange.setResponseBody(Streams.getBytes(httpConn.getErrorStream(), gzipped)); } finally { backendExchange.stop(); } // Stores infos backendExchange.setResponseCode(httpConn.getResponseCode()); backendExchange.setResponseHeaders(httpConn.getHeaderFields()); // Specific error code treatment switch (backendExchange.getResponseCode()) { case 0: // No response LOGGER.debug("ResponseCode = 0 !!!"); Requests.sendErrorServer(request, response, String.format(ProxyErrorConstants.EMPTY_RESPONSE, targetUrl.toString())); return; case 404: LOGGER.debug("404 returned"); Requests.sendErrorServer(request, response, String.format(ProxyErrorConstants.NOT_FOUND, targetUrl.toString()), 404); return; default: break; } // return response with filtered headers List<String> respHeadersToIgnore = new ArrayList<String>(RESP_HEADERS_TO_IGNORE); addResponseHeaders(response, backendExchange, respHeadersToIgnore); response.setStatus(backendExchange.getResponseCode()); response.getOutputStream().write(backendExchange.getResponseBody()); } catch (IllegalStateException e1) { // bad url Requests.sendErrorClient(request, response, e1.getMessage()); } catch (ClassCastException ex) { // bad url Requests.sendErrorClient(request, response, ex.getMessage()); } catch (IOException ex) { LOGGER.error("Backend call in ERROR"); // bad call Requests.sendErrorServer(request, response, ex.getMessage()); } catch (Exception ex) { LOGGER.error("Error during proxying : {}", ex); // protect from all exceptions Requests.sendInternalErrorServer(request, response, ex.getMessage()); } finally { LOGGER.trace("BackendExchange Hashcode : {}", Integer.toHexString(backendExchange.hashCode())); LOGGER.debug("BackendExchange : {}", backendExchange); if (httpConn != null) { try { httpConn.disconnect(); } catch (Exception ex) { LOGGER.warn("Error on disconnect {}", ex); } } } }
From source file:export.GarminUploader.java
private Status connectNew() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;//from ww w .j av a2 s . co m s.authMethod = Uploader.AuthMethod.USER_PASS; FormValues fv = new FormValues(); fv.put("service", "http://connect.garmin.com/post-auth/login"); fv.put("clientId", "GarminConnect"); fv.put("consumeServiceTicket", "false"); HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv); addCookies(conn); expectResponse(conn, 200, "Connection 1: "); getCookies(conn); getFormValues(conn); conn.disconnect(); // try again FormValues data = new FormValues(); data.put("username", username); data.put("password", password); data.put("_eventId", "submit"); data.put("embed", "true"); data.put("lt", formValues.get("lt")); conn = post("https://sso.garmin.com/sso/login", fv); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); postData(conn, data); expectResponse(conn, 200, "Connection 2: "); getCookies(conn); String html = getFormValues(conn); conn.disconnect(); /* this is really horrible */ int start = html.indexOf("?ticket="); if (start == -1) { throw new IOException("Invalid login, unable to locate ticket"); } start += "?ticket=".length(); int end = html.indexOf("'", start); String ticket = html.substring(start, end); // connection 3... fv.clear(); fv.put("ticket", ticket); conn = get("http://connect.garmin.com/post-auth/login", fv); conn.setInstanceFollowRedirects(false); addCookies(conn); expectResponse(conn, 302, "Connection 3: "); List<String> fields = conn.getHeaderFields().get("location"); getCookies(conn); // connection 4... conn = get(fields.get(0), null); conn.setInstanceFollowRedirects(false); addCookies(conn); expectResponse(conn, 302, "Connection 4: "); getCookies(conn); conn.disconnect(); return checkLogin(); }
From source file:com.dao.ShopThread.java
private String getPayKey(HttpURLConnection conn, String type) throws Exception { LogUtil.debugPrintf(""); String keyurl = conn.getURL().toString(); String postParams = getKeyDynamicParams(keyurl, type); HttpURLConnection loginConn = getHttpPostConn(keyurl); loginConn.setRequestProperty("Accept-Encoding", "deflate");// ?? loginConn.setRequestProperty("Referer", keyurl); loginConn.setRequestProperty("Host", "danbao.5173.com"); loginConn.setRequestProperty("Pragma", "no-cache"); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?keyHEADER===" + loginConn.getRequestProperties()); LogUtil.debugPrintf("?keypostParams===" + postParams); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);/*from ww w . j a va 2 s . c o m*/ wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(2000); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String payurl = response.toString(); LogUtil.debugPrintf("keyHtml:" + payurl); payurl = payurl.substring(payurl.indexOf("action") + "action".length(), payurl.indexOf("></form>")); payurl = payurl.substring(payurl.indexOf("\"") + 1, payurl.lastIndexOf("\"")); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("?key?HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { LogUtil.debugPrintf("?keycookie----------->"); } else { LogUtil.debugPrintf("?keycookie----------->"); LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } LogUtil.debugPrintf("?key?----------->"); return payurl; }
From source file:com.github.gcauchis.scalablepress4j.api.AbstractRestApi.java
/** * Call request for entity./*from w ww .ja va 2 s .c o m*/ * * @param <T> the generic type * @param url the url * @param requestMethod the http request method * @param request the request * @param responseType the response type * @param urlVariables the url variables * @return the response */ private <T> Response<T> forEntity(String url, String requestMethod, Object request, Class<T> responseType, Map<String, ?> urlVariables) { StringBuilder response = new StringBuilder(); HttpURLConnection connection = prepareConnection(url, requestMethod, urlVariables); try { // // Send request DataOutputStream wr = null; if (request != null) { String content = objectMapper.writeValueAsString(request); wr = new DataOutputStream(connection.getOutputStream()); wr.write(content.getBytes(StandardCharsets.UTF_8)); wr.flush(); } // Get Response BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } if (wr != null) { wr.close(); } rd.close(); log.trace("Response {}", response); } catch (IOException e) { log.error("Fail to send request", e); ErrorResponse errorResponse = new ErrorResponse(); try { errorResponse.setStatusCode(connection.getResponseCode() + ""); errorResponse.setMessage(connection.getResponseMessage()); } catch (IOException e1) { errorResponse.setStatusCode("500"); errorResponse.setMessage(e.getMessage()); } throw new ScalablePressBadRequestException(errorResponse); } Response<T> responseEntity = new Response<>(); responseEntity.headers = connection.getHeaderFields(); log.debug("Header: {}", responseEntity.headers); try { responseEntity.body = objectMapper.readValue(response.toString(), responseType); } catch (IOException e) { log.error("Fail to parse response", e); ErrorResponse errorResponse = null; try { log.error("Response error: {} {}", connection.getResponseCode(), connection.getResponseMessage()); errorResponse = objectMapper.readValue(response.toString(), ErrorResponse.class); } catch (IOException ioe) { log.error("Fail to parse error", ioe); } if (errorResponse != null) { log.error("Response error object: {}", errorResponse); throw new ScalablePressBadRequestException(errorResponse); } } return responseEntity; }
From source file:com.emc.ecs.smart.SmartUploader.java
/** * Does a standard PUT upload using HttpURLConnection. *///from w ww.ja va 2 s . com private void doSimpleUpload() { try { fileSize = Files.size(fileToUpload); HttpURLConnection conn = null; long start = System.currentTimeMillis(); try (DigestInputStream is = new DigestInputStream(Files.newInputStream(fileToUpload), MessageDigest.getInstance("MD5"))) { conn = (HttpURLConnection) uploadUrl.openConnection(); conn.setFixedLengthStreamingMode(fileSize); conn.setDoInput(true); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setUseCaches(false); conn.setRequestMethod(HttpMethod.PUT); conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM); OutputStream os = conn.getOutputStream(); byte[] buf = new byte[CHUNK_SIZE]; int len; while ((len = is.read(buf)) != -1) { os.write(buf, 0, len); bytesUploaded += len; printPercent(); } os.close(); if (conn.getResponseCode() != ClientResponse.Status.OK.getStatusCode()) { throw new RuntimeException("Unable to upload object content: status=" + conn.getResponseCode()); } else { List<String> eTags = conn.getHeaderFields().get(HttpHeaders.ETAG); if (eTags == null || eTags.size() < 1) { throw new RuntimeException("Unable to get ETag for uploaded data"); } else { byte[] sentMD5 = is.getMessageDigest().digest(); String eTag = eTags.get(0); byte[] gotMD5 = DatatypeConverter.parseHexBinary(eTag.substring(1, eTag.length() - 1)); if (!Arrays.equals(gotMD5, sentMD5)) { throw new RuntimeException("ETag doesn't match streamed data's MD5."); } } } } catch (IOException e) { throw new Exception("IOException while uploading object content after writing " + bytesUploaded + " of " + fileSize + " bytes: " + e.getMessage()); } finally { if (conn != null) conn.disconnect(); } long elapsed = System.currentTimeMillis() - start; printRate(fileSize, elapsed); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {//from www .ja va2 s. com URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>POST</code> method. * @param req servlet request/*from w w w. j a v a2s .c o m*/ * @param resp servlet response */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read POST data from incoming request, write to outgoing request BufferedInputStream in = new BufferedInputStream(req.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); // read result headers of POST, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } // read result data of POST, write out to response in = new BufferedInputStream(con.getInputStream()); out = new BufferedOutputStream(resp.getOutputStream()); for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); con.disconnect(); }
From source file:com.example.rtobase2.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w w w . j a v a2 s . co m*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }