List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:ai.eve.volley.Request.java
/** * Returns the raw POST or PUT body to be sent. * /* ww w . ja v a 2s .c om*/ * @throws AuthFailureError * in the event of auth failure */ public void getBody(HttpURLConnection connection) throws AuthFailureError { Map<String, String> params = getParams(); if (params != null && params.size() > 0) { byte[] bs = encodeParameters(params, getParamsEncoding()); try { if (bs != null) { connection.setDoOutput(true); connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(bs); out.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:ai.api.AIDataService.java
protected String doTextRequest(@NonNull final String endpoint, @NonNull final String requestJson, @Nullable final Map<String, String> additionalHeaders) throws MalformedURLException, AIServiceException { HttpURLConnection connection = null; try {/*from w w w .j a va 2 s . co m*/ final URL url = new URL(endpoint); final String queryData = requestJson; Log.d(TAG, "Request json: " + queryData); if (config.getProxy() != null) { connection = (HttpURLConnection) url.openConnection(config.getProxy()); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey()); connection.addRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.addRequestProperty("Accept", "application/json"); if (additionalHeaders != null) { for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } } connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(queryData, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); final String response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { if (connection != null) { try { final InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { final String errorString = IOUtils.toString(errorStream, Charsets.UTF_8); Log.d(TAG, "" + errorString); return errorString; } else { throw new AIServiceException("Can't connect to the api.ai service.", e); } } catch (final IOException ex) { Log.w(TAG, "Can't read error response", ex); } } Log.e(TAG, "Can't make request to the API.AI service. Please, check connection settings and API access token.", e); throw new AIServiceException( "Can't make request to the API.AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.runnerup.export.RuntasticUploader.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;// w ww .ja v a 2 s. co m if ((s = connect()) != Status.OK) { return s; } StringWriter writer = new StringWriter(); TCX tcx = new TCX(db); HttpURLConnection conn = null; try { Pair<String, Sport> res = tcx.exportWithSport(mID, writer); Sport sport = res.second; String filename = String.format("activity%s%d.tcx", Long.toString(Math.round(1000 * Math.random())), mID); String url = UPLOAD_URL + "?authenticity_token=" + URLEncode(authToken) + "&qqfile=" + filename; conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Host", "www.runtastic.com"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.addRequestProperty("X-File-Name", filename); conn.addRequestProperty("Content-Type", "application/octet-stream"); addRequestHeaders(conn); OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(writer.toString().getBytes()); out.flush(); out.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ret = parse(in); getCookies(conn); if (ret == null || !ret.has("success") || !ret.getBoolean("success")) { System.out.println("ret: " + ret); throw new JSONException("Unexpected json return"); } String tmp = ret.getString("content"); final String name = "name='"; int i1 = tmp.indexOf(name); if (i1 < 0) { System.out.println("ret: " + ret); throw new JSONException("Unexpected json return"); } i1 += name.length(); int i2 = tmp.indexOf('\'', i1); String import_id = tmp.substring(i1, i2); System.out.println("import_id: " + import_id); conn.disconnect(); if (sport != null && sport != Sport.RUNNING && sport2runtasticMap.containsKey(sport)) { conn = (HttpURLConnection) new URL(UPDATE_SPORTS_TYPE).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); addRequestHeaders(conn); FormValues fv = new FormValues(); fv.put("authenticity_token", authToken); fv.put("data_import_id", import_id); fv.put("sport_type_id", sport2runtasticMap.get(sport).toString()); fv.put("user_id", userId.toString()); postData(conn, fv); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); System.out.println("code: " + responseCode + ", html: " + getFormValues(conn)); conn.disconnect(); } logout(); return Status.OK; } catch (IOException ex) { s.ex = ex; } catch (JSONException e) { s.ex = e; } if (s.ex != null) System.err.println("ex: " + s.ex); if (conn != null) conn.disconnect(); s = Status.ERROR; return s; }
From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java
public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml, String soapAction) throws IOException, SOAPException { URI serviceLocation;/*from w w w . jav a 2s. c o m*/ try { serviceLocation = new URI(location); } catch (URISyntaxException e) { throw new IOException("Invalid uri for artifact resolve: " + location); } if (log.isDebugEnabled()) log.debug("serviceLocation..:" + serviceLocation); if (log.isDebugEnabled()) log.debug("SOAP Request: " + xml); HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection(); if (c instanceof HttpsURLConnection) { HttpsURLConnection sc = (HttpsURLConnection) c; if (ignoreCertPath) { sc.setSSLSocketFactory(new DummySSLSocketFactory()); sc.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } } c.setAllowUserInteraction(false); c.setDoInput(true); c.setDoOutput(true); c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length); c.setRequestMethod("POST"); c.setReadTimeout(20000); c.setConnectTimeout(30000); addContentTypeHeader(xml, c); c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\""); if (username != null && password != null) { c.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES)); } OutputStream outputStream = c.getOutputStream(); IOUtils.write(xml, outputStream, "UTF-8"); outputStream.flush(); outputStream.close(); if (c.getResponseCode() == 200) { InputStream inputStream = c.getInputStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP response: " + result); XMLObject res = SAMLUtil.unmarshallElementFromString(result); Envelope envelope = (Envelope) res; if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) { log.warn( "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server"); throw new SOAPException(c.getResponseCode(), result); } return envelope; } else { log.debug("Response code: " + c.getResponseCode()); InputStream inputStream = c.getErrorStream(); String result = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); if (log.isDebugEnabled()) log.debug("Server SOAP fault: " + result); throw new SOAPException(c.getResponseCode(), result); } }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
@Override public Status upload(SQLiteDatabase db, final long mID) { Status s;//w w w . j av a 2 s . c o m if ((s = connect()) != Status.OK) { return s; } /** * Get the fitnessActivities end-point */ HttpURLConnection conn = null; Exception ex; try { URL newurl = new URL(REST_URL + fitnessActivitiesUrl); Log.e(Constants.LOG, "url: " + newurl.toString()); conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-type", "application/vnd.com.runkeeper.NewFitnessActivity+json"); RunKeeper rk = new RunKeeper(db); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); rk.export(mID, w); w.flush(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.disconnect(); conn = null; if (responseCode >= HttpStatus.SC_OK && responseCode < HttpStatus.SC_MULTIPLE_CHOICES) { s = Status.OK; s.activityId = mID; return s; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (ex != null) { Log.e(getName(), "Failed to upload: " + ex.getMessage()); } if (conn != null) { conn.disconnect(); } s = Synchronizer.Status.ERROR; s.ex = ex; s.activityId = mID; return s; }
From source file:core.AbstractTest.java
private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) { Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: " + mParameters + "\nPayload: " + payload + "\n"); HttpURLConnection conn = null; BufferedReader br = null;//from ww w . j a v a2s.co m int nRet = 0; boolean fIsMultipart = false; try { setStatusCode(-1); setResponse(null); conn = getHttpConnection(sUrl, sMethod); if (mHeaders.size() > 0) { Set<String> keys = mHeaders.keySet(); for (String sKey : keys) { conn.addRequestProperty(sKey, mHeaders.get(sKey)); if (sKey.equals(HTTP.CONTENT_TYPE)) { if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) { fIsMultipart = true; } } } } if (payload != null || mParameters != null) { DataOutputStream out = new DataOutputStream(conn.getOutputStream()); try { if (payload != null) { //conn.setRequestProperty("Content-Length", "" + node.toString().length()); out.writeBytes(payload.toString()); } if (mParameters != null) { Set<String> sKeys = mParameters.keySet(); if (fIsMultipart) { out.writeBytes("--" + BOUNDARY + "\r\n"); } for (String sKey : sKeys) { if (fIsMultipart) { out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n"); out.writeBytes(mParameters.get(sKey)); out.writeBytes("\r\n"); out.writeBytes("--" + BOUNDARY + "--\r\n"); } else { out.writeBytes(URLEncoder.encode(sKey, "UTF-8")); out.writeBytes("="); out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8")); out.writeBytes("&"); } } if (fIsMultipart) { if (nvpFile != null) { File f = Play.application().getFile(nvpFile.getName()); if (f == null) { assertFail("Cannot find file <" + nvpFile.getName() + ">"); } FileBody fb = new FileBody(f); out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE + "\";filename=\"" + fb.getFilename() + "\"\r\n"); out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n"); out.write(getResource(nvpFile.getName())); } out.writeBytes("\r\n--" + BOUNDARY + "--\r\n"); } } } catch (Exception ex) { assertFail("Send request: " + ex.getMessage()); } finally { try { out.flush(); } catch (Exception ex) { } try { out.close(); } catch (Exception ex) { } } } nRet = conn.getResponseCode(); setStatusCode(nRet); if (nRet / 100 != 2) { if (conn.getErrorStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } } else { if (conn.getInputStream() != null) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } } if (br != null) { String temp = null; StringBuilder sb = new StringBuilder(1024); while ((temp = br.readLine()) != null) { sb.append(temp).append("\n"); } setResponse(sb.toString().trim()); } Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n"); } catch (Exception ex) { assertFail("httpRequest: " + ex.getMessage()); } finally { if (br != null) { try { br.close(); } catch (Exception ex) { } } if (conn != null) { conn.disconnect(); } } return nRet; }
From source file:org.okj.im.core.service.QQHttpService.java
/** * HTTP/* w w w .ja va 2s . c o m*/ * @param url * @param method * @param exParam * @return */ protected HttpURLConnection connect(String url, String method, ExParam exParam) { HttpURLConnection conn = null; try { URL serverUrl = new URL(url); if (proxyHost != null && proxyPort != null && !"".equals(proxyHost)) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpURLConnection) serverUrl.openConnection(proxy); } else { conn = (HttpURLConnection) serverUrl.openConnection(); } conn.setConnectTimeout(60000); conn.setReadTimeout(100000); System.setProperty("sun.net.client.defaultConnectTimeout", "60000"); System.setProperty("sun.net.client.defaultReadTimeout", "100000"); conn.setRequestMethod(method);// "POST" ,"GET" conn.addRequestProperty("Referer", refer); conn.addRequestProperty("Cookie", exParam.getCookie()); conn.addRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Accept-Language", "zh-cn"); conn.addRequestProperty("Accept-Encoding", "gzip, deflate"); conn.addRequestProperty("Cache-Control", "no-cache"); conn.addRequestProperty("Accept-Charset", "UTF-8;"); conn.addRequestProperty("Host", "d.web2.qq.com"); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19"); if (StringUtils.equalsIgnoreCase(method, HttpMethod.GET)) { conn.setDoInput(true); conn.connect(); } else if (StringUtils.equalsIgnoreCase(method, HttpMethod.POST)) { conn.setDoInput(true); conn.setDoOutput(true); if (StringUtils.isNotBlank(exParam.getFilename())) { conn.setRequestProperty("Content-Type", "multipart/form-data"); } conn.connect(); if (StringUtils.isNotBlank(exParam.getContents())) { conn.getOutputStream().write(exParam.getContents().getBytes()); } // if (StringUtils.isNotBlank(exParam.getFilename())) { uploadFile(exParam.getFilename(), conn.getOutputStream()); LogUtils.info(LOGGER, "?, filename={0}", exParam.getFilename()); } } else { LogUtils.warn(LOGGER, "your method is not implement"); //throw new RuntimeException("your method is not implement"); } } catch (Exception ex) { LogUtils.error(LOGGER, "httpclient?", ex); } return conn; }
From source file:org.runnerup.export.RuntasticSynchronizer.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;/* ww w .j ava 2 s . com*/ if ((s = connect()) != Status.OK) { return s; } StringWriter writer = new StringWriter(); TCX tcx = new TCX(db); HttpURLConnection conn = null; try { Pair<String, Sport> res = tcx.exportWithSport(mID, writer); Sport sport = res.second; String filename = String.format("activity%s%d.tcx", Long.toString(Math.round(1000 * Math.random())), mID); String url = UPLOAD_URL + "?authenticity_token=" + SyncHelper.URLEncode(authToken) + "&qqfile=" + filename; conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Host", "www.runtastic.com"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.addRequestProperty("X-File-Name", filename); conn.addRequestProperty("Content-Type", "application/octet-stream"); addRequestHeaders(conn); OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(writer.toString().getBytes()); out.flush(); out.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ret = SyncHelper.parse(in); getCookies(conn); if (ret == null || !ret.has("success") || !ret.getBoolean("success")) { Log.i(getName(), "ret: " + ret); throw new JSONException("Unexpected json return"); } String tmp = ret.getString("content"); final String name = "name='"; int i1 = tmp.indexOf(name); if (i1 < 0) { Log.i(getName(), "ret: " + ret); throw new JSONException("Unexpected json return"); } i1 += name.length(); int i2 = tmp.indexOf('\'', i1); String import_id = tmp.substring(i1, i2); Log.i(getName(), "import_id: " + import_id); conn.disconnect(); if (sport != null && sport != Sport.RUNNING && sport2runtasticMap.containsKey(sport)) { conn = (HttpURLConnection) new URL(UPDATE_SPORTS_TYPE).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.addRequestProperty("X-Requested-With", "XMLHttpRequest"); addRequestHeaders(conn); FormValues fv = new FormValues(); fv.put("authenticity_token", authToken); fv.put("data_import_id", import_id); fv.put("sport_type_id", sport2runtasticMap.get(sport).toString()); fv.put("user_id", userId.toString()); SyncHelper.postData(conn, fv); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); Log.i(getName(), "code: " + responseCode + ", html: " + getFormValues(conn)); conn.disconnect(); } logout(); s = Status.OK; s.activityId = mID; return s; } catch (IOException ex) { s = Status.ERROR; s.ex = ex; } catch (JSONException e) { s = Status.ERROR; s.ex = e; } if (s.ex != null) Log.e(getName(), "ex: " + s.ex); if (conn != null) conn.disconnect(); s.activityId = mID; return s; }
From source file:org.runnerup.export.Endomondo.java
@Override public Status connect() { if (isConfigured()) { return Status.OK; }/*from w ww . j a va 2 s . c om*/ Status s = Status.NEED_AUTH; s.authMethod = Uploader.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } /** * Generate deviceId */ deviceId = UUID.randomUUID().toString(); Exception ex = null; HttpURLConnection conn = null; logout(); try { /** * */ String login = AUTH_URL; FormValues kv = new FormValues(); kv.put("email", username); kv.put("password", password); kv.put("v", "2.4"); kv.put("action", "pair"); kv.put("deviceId", deviceId); kv.put("country", "N/A"); conn = (HttpURLConnection) new URL(login).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject res = parseKVP(in); conn.disconnect(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == 200 && "OK".contentEquals(res.getString("_0")) && res.has("authToken")) { authToken = res.getString("authToken"); return Status.OK; } System.err.println("FAIL: code: " + responseCode + ", msg=" + amsg + ", res=" + res.toString()); return s; } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:vc.fq.FanfouExporter.ExportTread.java
/** * GET?API//from w ww . j av a2 s . com * @param strURL * @param page * @return */ public HttpURLConnection connectAPI(String strURL, int page) { long timestamp = System.currentTimeMillis() / 1000; long nonce = System.nanoTime(); String pageID = String.valueOf(page); StringBuffer strBuf = new StringBuffer(210); strBuf.append("count=60"); strBuf.append("&oauth_consumer_key=").append(consumer_key); strBuf.append("&oauth_nonce=").append(nonce); strBuf.append("&oauth_signature_method=HMAC-SHA1"); strBuf.append("&oauth_timestamp=").append(timestamp); strBuf.append("&oauth_token=").append(oauth_token); String params = strBuf.toString(); System.out.println(params.length()); params = params + "&page=" + pageID; try { params = "GET&" + URLEncoder.encode(strURL, "UTF-8") + "&" + URLEncoder.encode(params, "UTF-8"); } catch (UnsupportedEncodingException e) { setLog("?"); } String sig = generateSignature(params, oauth_token_secret); strBuf = new StringBuffer(280); strBuf.append("OAuth realm=\"Fantalker\",oauth_consumer_key=\""); strBuf.append(consumer_key); strBuf.append("\",oauth_signature_method=\"HMAC-SHA1\""); strBuf.append(",oauth_timestamp=\"").append(timestamp).append("\""); strBuf.append(",oauth_nonce=\"").append(nonce).append("\""); strBuf.append(",oauth_signature=\"").append(sig).append("\""); strBuf.append(",oauth_token=\"").append(oauth_token).append("\""); String authorization = strBuf.toString(); strURL = strURL + "?count=60&page=" + pageID; try { URL url = new URL(strURL); HttpURLConnection connection; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.addRequestProperty("Authorization", authorization); connection.connect(); return connection; } catch (SocketTimeoutException e) { setLog(" " + e.getMessage()); } catch (IOException e) { setLog(e.getMessage()); } return null; }