/** * 取得URL * * @param context * @param getRequest * @return request URL */ public String getRequestUrl(Context context, HttpPost getRequest) { final StringBuilder urlBuilder = new StringBuilder(); ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkinfo = connManager.getActiveNetworkInfo(); String extraInfo = null; if (networkinfo != null) { extraInfo = networkinfo.getExtraInfo(); } if (extraInfo != null && (extraInfo.equals(CMWAP) || extraInfo.equals(CTWAP) || extraInfo.equals(UNIWAP) || extraInfo.equals(GWAP))) { urlBuilder.append(X_OFFLINE_HOST); isWapState = true; } else { urlBuilder.append(SCHEME); urlBuilder.append(getRequest.getURI().getHost()); int port = getRequest.getURI().getPort(); if (port != -1) { urlBuilder.append(PORT_TOKEN); urlBuilder.append(port); } } urlBuilder.append(getRequest.getURI().getPath()); final String query = getRequest.getURI().getQuery(); if (!TextUtils.isEmpty(query)) { urlBuilder.append("?"); urlBuilder.append(query); } return urlBuilder.toString(); }
/** * Sets basic authentication on web request using plain credentials * * @param username The plain text username * @param password The plain text password */ public void setBasicAuthentication(String username, String password) { ((DefaultHttpClient) client) .getCredentialsProvider() .setCredentials( new AuthScope( postMethod.getURI().getHost(), postMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); }
private boolean loginWithAccessCode( DefaultHttpClient httpClient, HttpContext context, String bankAccount, String accessCode) throws IOException, RetrieverException { String logonToken = requestLogonToken( httpClient, context, "https://bankservices.rabobank.nl/services/balanceviewsettings/v1"); HttpPost post = new HttpPost("https://bankservices.rabobank.nl/auth/logonac/v2/"); final String requestXml = String.format(AC_LOGIN, accessCode, bankAccount, logonToken); StringEntity stringEntity = new StringEntity(requestXml, "application/xml", "UTF-8"); post.setEntity(stringEntity); post.setHeader("Content-Type", "application/xml"); post.setHeader("Accept", "application/xml"); HttpResponse response = httpClient.execute(post, context); if (response.getStatusLine().getStatusCode() != 200) { post.abort(); throw new RetrieverException( "Expected HTTP 200 from " + post.getURI() + ", received " + response.getStatusLine()); } post.abort(); return true; }
@Override protected Boolean doInBackground(String... params) { boolean result = false; try { InqChangePasswordRequest inqChangePasswordRequest = new InqChangePasswordRequest(); String s = HttpClientUtil.getObjectMapper(ctx).writeValueAsString(inqChangePasswordRequest); s = CipherUtil.encryptTripleDES(s, CipherUtil.PASSWORD); Log.d(TAG, "Request: " + s); StringEntity entity = new StringEntity(s); HttpPost post = new HttpPost(HttpClientUtil.URL_BASE + HttpClientUtil.URL_REFRESHING_LIST_MALL); post.setHeader(HttpClientUtil.CONTENT_TYPE, HttpClientUtil.JSON); post.setEntity(entity); // Execute HTTP request Log.d(TAG, "Executing request: " + post.getURI()); HttpResponse response = client.execute(post); HttpEntity respEntity = response.getEntity(); respString = EntityUtils.toString(respEntity); result = true; } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException : " + e); respString = ctx.getResources().getString(R.string.message_unexpected_error_message_server); cancel(true); } catch (IOException e) { Log.e(TAG, "IOException : " + e); respString = ctx.getResources().getString(R.string.message_no_internet_connection); cancel(true); } catch (Exception e) { Log.e(TAG, "Exception : " + e); respString = ctx.getResources().getString(R.string.message_unexpected_error_message_server); cancel(true); } return result; }
private void changeServer(HttpPost httpPost, String sufix) { String ip = RoundRobin.getInstance() .getAnotherIP( this.fragment.getActivity().getApplicationContext(), httpPost.getURI().getHost()); httpPost.setURI(URI.create(ip + sufix)); }
private String getSignatureBaseString(HttpPost req, OAuthParameters params) { final String method = req.getMethod(); final String url = Uri.encode(req.getURI().toString()); final String sortedParams = Uri.encode(params.getSortedEncodedParamsAsString()); return method + '&' + url + '&' + sortedParams; }
@SuppressWarnings({"unchecked"}) @Override protected T doInBackground(Object... params) { HttpClient httpclient = new DefaultHttpClient(); Log.d("FetchJsonRequest", Constants.CEKILIS_URL + path); HttpPost httppost = new HttpPost(Constants.CEKILIS_URL + path); // // httppost.addHeader("Cookie","ASP.NET_SessionId="+asp);//"ASP.NET_SessionId=qxa0dzhlq02usf0pix3l3hrw"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); for (int i = 0; i < params.length; i = i + 2) { String name, value; List<String> valueList; if (params[i].toString().lastIndexOf("#") == params[i].toString().length() - 1) { name = params[i].toString().substring(0, params[i].toString().length() - 1); valueList = ((List<String>) params[i + 1]); for (String s : valueList) { nameValuePairs.add(new BasicNameValuePair(name, s)); } } else { name = params[i].toString(); value = params[i + 1].toString(); nameValuePairs.add(new BasicNameValuePair(name, value)); } } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); Log.i("piyango", httppost.getURI().toString() + "?" + nameValuePairs.toString()); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != 200) { // Meaning an error has occured return null; } InputStream is = response.getEntity().getContent(); // Compatible with JavaScript's Date format Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'hh:mm:ss.sss'Z'").create(); Reader reader = new InputStreamReader(is); // Parse the fetched JSON object to a Java object T myObj = gson.fromJson(reader, object); Log.d("Recieved Object", myObj.toString()); return myObj; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.d("FetchJsonRequestFail", Constants.CEKILIS_URL + path); return null; }
/* * makes an access token. */ public String signRequest(HttpPost post) throws AuthException { URI uri = post.getURI(); String path = uri.getRawPath(); String query = uri.getRawQuery(); HttpEntity entity = post.getEntity(); byte[] secretKey = this.secretKey.getBytes(); javax.crypto.Mac mac = null; try { mac = javax.crypto.Mac.getInstance("HmacSHA1"); } catch (NoSuchAlgorithmException e) { throw new AuthException("No algorithm called HmacSHA1!", e); } SecretKeySpec keySpec = new SecretKeySpec(secretKey, "HmacSHA1"); try { mac.init(keySpec); mac.update(path.getBytes()); } catch (InvalidKeyException e) { throw new AuthException("You've passed an invalid secret key!", e); } catch (IllegalStateException e) { throw new AuthException(e); } if (query != null && query.length() != 0) { mac.update((byte) ('?')); mac.update(query.getBytes()); } mac.update((byte) '\n'); if (entity != null) { org.apache.http.Header ct = entity.getContentType(); if (ct != null && ct.getValue() == "application/x-www-form-urlencoded") { ByteArrayOutputStream w = new ByteArrayOutputStream(); try { entity.writeTo(w); } catch (IOException e) { throw new AuthException(e); } mac.update(w.toByteArray()); } } byte[] digest = mac.doFinal(); byte[] digestBase64 = EncodeUtils.urlsafeEncodeBytes(digest); StringBuffer b = new StringBuffer(); b.append(this.accessKey); b.append(':'); b.append(new String(digestBase64)); return b.toString(); }
private String doPostForString(String url, List<BasicNameValuePair> params) { InputStream is = null; InputStreamReader in = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); // 使用DefaultHttpClient创建HttpClient实例 HttpPost post = new HttpPost(url); // 构建HttpPost UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 使用编码构建Post实体 post.setEntity(entity); // 执行Post方法 if (paramsProperty != null) { for (BasicNameValuePair basic : paramsProperty) { post.setHeader(basic.getName(), basic.getValue()); } } HttpResponse response = httpClient.execute(post); // 获取返回实体 is = response.getEntity().getContent(); in = new InputStreamReader(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int lenth = 0; while ((lenth = is.read(buffer)) != -1) { bos.write(buffer, 0, lenth); bos.flush(); } bos.close(); String json = bos.toString(); if (isLog) { LogFileHelper.getInstance().i(TAG, post.getURI().toString()); LogFileHelper.getInstance().i(TAG, json); } return json; } catch (Exception e) { // TODO Auto-generated catch block LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage()); } // 使用finally块来关闭输出流、输入流 finally { try { if (is != null) { is.close(); } if (in != null) { in.close(); } } catch (IOException e) { LogFileHelper.getInstance().e(getClass().getSimpleName(), e.getMessage()); } } return null; }
/** * Sets basic authentication on web request using plain credentials * * @param username The plain text username * @param password The plain text password * @param doPreemptiveAuth Select here whether to authenticate without it being requested first by * the server. */ public void setBasicAuthentication(String username, String password, boolean doPreemptiveAuth) { // This code required to trigger the patch created by erickok in issue #6 if (doPreemptiveAuth = true) { this.httpPreAuth = doPreemptiveAuth; this.username = username; this.password = password; } else { ((DefaultHttpClient) client) .getCredentialsProvider() .setCredentials( new AuthScope( postMethod.getURI().getHost(), postMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); } }
public static ResponseResult httpByPostJSONObjSSL( String url, Map<String, String> params, String paramsCharset, String resultCharset) { if (url == null || "".equals(url)) { return null; } ResponseResult responseObject = null; String responseStr = null; HttpClient httpClient = null; HttpPost hp = null; try { httpClient = getNewHttpClient(); hp = new HttpPost(url); if (params != null && !params.isEmpty()) { String content = params.get("content"); if (!StringUtils.isEmpty(content)) { StringEntity s = new StringEntity(content.toString(), LSystem.encoding); s.setContentEncoding("HTTP.UTF_8"); s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); hp.setEntity(s); } } HttpResponse response = httpClient.execute(hp); if (response != null) { responseObject = new ResponseResult(); responseObject.setUri(hp.getURI().toString()); responseObject.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) { if (resultCharset == null || "".equals(resultCharset)) { responseStr = EntityUtils.toString(response.getEntity(), LSystem.encoding); } else { responseStr = EntityUtils.toString(response.getEntity(), resultCharset); } } else { responseStr = null; } responseObject.setResult(responseStr); } } catch (Exception e) { e.printStackTrace(); } finally { abortConnection(hp, httpClient); } return responseObject; }
private String requestLogonToken( DefaultHttpClient httpClient, HttpContext context, String service) throws IOException, RetrieverException { HttpPost post = new HttpPost("https://bankservices.rabobank.nl/auth/logoninfo/v1/"); final Calendar nowGmt = Calendar.getInstance(TimeZone.getTimeZone("GMT")); final String formattedDate = new SimpleDateFormat("yyyyMMddHHmm").format(nowGmt.getTime()); final String requestXml = String.format(LOGON_INFO, formattedDate, service); StringEntity stringEntity = new StringEntity(requestXml, "application/xml", "UTF-8"); post.setEntity(stringEntity); post.setHeader("Content-Type", "application/xml"); post.setHeader("Accept", "application/xml"); HttpResponse response = httpClient.execute(post, context); if (response.getStatusLine().getStatusCode() != 200) { post.abort(); throw new RetrieverException( "Expected HTTP 200 from " + post.getURI() + ", received " + response.getStatusLine()); } InputStream contentStream = null; try { HttpEntity entity = response.getEntity(); contentStream = entity.getContent(); InputStreamReader isReader = new InputStreamReader(contentStream, "UTF-8"); BufferedReader reader = new BufferedReader(isReader); String line; String logonToken = null; while ((line = reader.readLine()) != null) { Matcher m = LOGON_TOKEN.matcher(line); if (m.matches()) { logonToken = m.group(1); } } return logonToken; } finally { if (contentStream != null) { contentStream.close(); } } }
public static ResponseResult postSSL( String url, Map<String, String> params, String paramsCharset, String resultCharset, HttpClient httpClient) { if (url == null || "".equals(url)) { return null; } ResponseResult responseObject = null; String responseStr = null; HttpPost hp = null; try { hp = new HttpPost(url); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } hp.setEntity(new UrlEncodedFormEntity(formParams, LSystem.encoding)); HttpResponse response = httpClient.execute(hp); if (response != null) { responseObject = new ResponseResult(); responseObject.setUri(hp.getURI().toString()); responseObject.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) { if (resultCharset == null || "".equals(resultCharset)) { responseStr = EntityUtils.toString(response.getEntity(), LSystem.encoding); } else { responseStr = EntityUtils.toString(response.getEntity(), resultCharset); } } else { responseStr = null; } responseObject.setResult(responseStr); } } catch (Exception e) { e.printStackTrace(); } finally { abortConnection(hp); } return responseObject; }
public String createRoster(Roster roster) throws Exception { LOGGER.debug("Inside createRoster"); loadProperties(); DefaultHttpClient httpClient = null; try { String method = "createRoster"; httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url + "/roster/" + method); LOGGER.debug("END POINT URL: " + postRequest.getURI()); Map<String, Object> values = new HashMap<String, Object>(); values.put("roster_id", roster.getId()); values.put("roster_type", roster.getType()); values.put("roster_name", roster.getName()); values.put("station_ids", roster.getStations()); values.put("employee_ids", roster.getEmployees()); String body = "{\"" + method + "\": " + OBJECT_MAPPER.writeValueAsString(values) + "}"; LOGGER.debug("Request body: " + body); StringEntity entity = new StringEntity(body); entity.setContentType("application/json"); postRequest.setEntity(entity); HttpResponse response = httpClient.execute(postRequest); String string = IOUtils.toString(response.getEntity().getContent()); System.out.println("Response body Roster: " + string); LOGGER.debug("Response body: " + string); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } System.out.println("Roster Done"); httpClient.getConnectionManager().shutdown(); return string; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpClient.close(); } return null; }
/** post方式提交表单(模拟用户登录请求) */ public void postForm() { // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action"); // 创建参数队列 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "admin")); formparams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8")); System.out.println("--------------------------------------"); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
@Test public void httpclientTest() { // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost(POST_URL); String secrectKey = null; try { secrectKey = AESCoder.initKeyString(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { byte[] secrectKyeByteArray = secrectKey.getBytes(); byte[] encryptByPublicKey = RSACoder.encryptByPublicKey(secrectKyeByteArray, publicKey); httppost.setEntity(new ByteArrayEntity(encryptByPublicKey)); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); // if (entity != null) { // System.out.println("--------------------------------------"); // String responseString = EntityUtils.toString(entity); // System.out.println("Response content: " + responseString); // System.out.println("--------------------------------------"); try { byte[] input = AESCoder.decrypt(IOUtils.toByteArray(response.getEntity().getContent()), secrectKey); String serverData = new String(input); System.out.println("server data: " + serverData); org.junit.Assert.assertNotNull(input); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private HttpConnectResult getResponseFromWebService( final String url, final int method, final Map<String, String> params, final ArrayList<Header> headerArray) throws HttpHelperException, IllegalArgumentException { // validace vstupu if (url == null) { Log.e(TAG, "getResponseFromWebService - Compulsory Parameter : request URL has not been set"); throw new IllegalArgumentException("Request URL has not been set"); } if (method != METHOD_GET && method != METHOD_POST) { Log.e(TAG, "getResponseFromWebService - Request method must be METHOD_GET or METHOD_POST"); throw new IllegalArgumentException( "getResponseFromWebService - Request method must be METHOD_GET or METHOD_POST"); } // pripojeni a ziskani odpovedi HttpResponse response = null; switch (method) { default: case METHOD_GET: try { HttpGet httpGet = new HttpGet(constructUrlRequest(url, params)); // pokud jsou hlavicky tak je pripoji k dotazu if (headerArray != null && !headerArray.isEmpty()) { final int headersLength = headerArray.size(); for (int i = 0; i < headersLength; i++) { httpGet.addHeader(headerArray.get(i)); } } Log.i(TAG, "Executing http query: " + httpGet.getURI().toString()); response = client.execute(httpGet); } catch (SocketTimeoutException e) { Log.w(TAG, "Connection timeout reached!"); throw new HttpHelperException("Connection timeout reached!"); } catch (UnsupportedEncodingException e) { throw new HttpHelperException("UnsupportedEncodingException"); } catch (ClientProtocolException e) { throw new HttpHelperException("ClientProtocolException"); } catch (IOException e) { throw new HttpHelperException("IOException"); } break; case METHOD_POST: try { HttpPost httpPost = new HttpPost(constructUrlRequest(url, params)); if (headerArray != null && !headerArray.isEmpty()) { final int headersLength = headerArray.size(); for (int i = 0; i < headersLength; i++) { httpPost.addHeader(headerArray.get(i)); } } Log.i(TAG, "Executing http query: " + httpPost.getURI().toString()); response = client.execute(httpPost); } catch (SocketTimeoutException e) { Log.w(TAG, "Connection timeout reached!"); throw new HttpHelperException("Connection timeout reached!"); } catch (UnsupportedEncodingException e) { throw new HttpHelperException("UnsupportedEncodingException"); } catch (ClientProtocolException e) { throw new HttpHelperException("ClientProtocolException"); } catch (IOException e) { throw new HttpHelperException("IOException"); } break; } final HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { try { result = convertStreamToString(entity.getContent(), method, (int) entity.getContentLength()); Log.i(TAG, "Response received: " + result); } catch (IllegalStateException e) { throw new HttpHelperException("IllegalStateException"); } catch (IOException e) { throw new HttpHelperException("IOException"); } } // vrati novy objekt HttpConnectResult nebo null HttpConnectResult httpResult = new HttpConnectResult(response.getAllHeaders(), result); if (httpResult.getStatus() != HttpConnectResult.Status.STATUS_OK) { Log.w(TAG, "Http response status is " + httpResult.getStatus().name()); throw new HttpHelperException("Http response statuts is not 200 OK."); } return (result != null) ? new HttpConnectResult(response.getAllHeaders(), result) : null; }
protected HttpPost postRolesMethod(final String param) { final HttpPost post = new HttpPost(serverAddress + param + "/" + SUFFIX); logger.debug("POST: {}", post.getURI()); return post; }