@Override protected String doInBackground(String... params) { byte[] result = null; String str = ""; HttpClient client = new DefaultHttpClient(); // HttpGet request = new // HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"+mSettings.getString(APP_PREFERENCES_TOKENID,"tokenId")); HttpGet request = new HttpGet("https://backfinecar-renatdk.c9.io/api/Cars"); HttpResponse response; try { response = client.execute(request); result = EntityUtils.toByteArray(response.getEntity()); str = new String(result, "UTF-8"); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str; }
public String sendLoginData(LoginData data) { String responseMessage = null; try { System.out.println("SENDING >>>>>>>>>"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://system.smartsales.bg/user/android_login/"); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("email", data.getEmail())); nameValuePairs.add(new BasicNameValuePair("password", data.getPassword())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); responseMessage = EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); } return responseMessage; }
@Override public void run() { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://localhost:8080/crawler/main"); httpGet.setConfig(RequestConfig.custom().setConnectTimeout(10000).build()); httpGet.setConfig(RequestConfig.custom().setSocketTimeout(5000).build()); int statusCode = 0; try { HttpResponse response = httpClient.execute(httpGet); statusCode = response.getStatusLine().getStatusCode(); while (statusCode != HttpStatus.SC_OK) { Thread.sleep(1000); response = httpClient.execute(httpGet); statusCode = response.getStatusLine().getStatusCode(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } ExtLogger.info("multi-thread start"); }
/** A simple test to see if multiple datasets are parsed successfully. */ @Test public void testAddedDatasets() throws Exception { when(client.execute(argThat(HttpGetMatcher.matchUrl("http://localhost/nmr?op=capabilities")))) .thenReturn(prepareResponse(200, "tapir/capabilities1.xml")); when(client.execute(argThat(HttpGetMatcher.matchUrl("http://localhost/nmr")))) .thenReturn(prepareResponse(200, "tapir/metadata1.xml")); when(client.execute( argThat( HttpGetMatcher.matchUrl( "http://localhost/nmr?op=s&t=http%3A%2F%2Frs.gbif.org%2Ftemplates%2Ftapir%2Fdwc%2F1.4%2Fsci_name_range.xml&count=true&start=0&limit=1&lower=AAA&upper=zzz")))) .thenReturn(prepareResponse(200, "tapir/search1.xml")); SyncResult syncResult = synchroniser.syncInstallation(installation, new ArrayList<Dataset>()); assertThat(syncResult.deletedDatasets).isEmpty(); assertThat(syncResult.existingDatasets).isEmpty(); assertThat(syncResult.addedDatasets).hasSize(1); assertThat(syncResult.addedDatasets.get(0).getContacts()).hasSize(2); assertThat(syncResult.addedDatasets.get(0).getMachineTags()).hasSize(2); // Assert the declared record count machine tag was found, and that its value was 167348 MachineTag count = null; for (MachineTag tag : syncResult.addedDatasets.get(0).getMachineTags()) { if (tag.getName().equalsIgnoreCase(Constants.DECLARED_COUNT)) { count = tag; } } assertThat(count).isNotNull(); assertThat(Integer.valueOf(count.getValue())).isEqualTo(167348); }
protected Void doInBackground(String... params) { /* * Insert */ try { HttpClient client = new DefaultHttpClient(); String postUrl; postUrl = "http://naddola.cafe24.com/insertWish.php"; HttpPost post = new HttpPost(postUrl); // 전달인자 List params2 = new ArrayList(); params2.add(new BasicNameValuePair("email", setting.getID())); params2.add(new BasicNameValuePair("title", myWishWeb.getTitle())); params2.add(new BasicNameValuePair("price", myWishWeb.getPrice() + "")); params2.add(new BasicNameValuePair("wish", myWishWeb.getWish() + "")); params2.add(new BasicNameValuePair("image", myWishWeb.getImagePath() + "")); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params2, HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePost = client.execute(post); HttpEntity resEntity = responsePost.getEntity(); } catch (Exception e) { e.printStackTrace(); } /* * Select */ try { HttpClient client = new DefaultHttpClient(); String postUrl; postUrl = "http://naddola.cafe24.com/getLastMyWish.php"; HttpPost post = new HttpPost(postUrl); // 전달인자 List params2 = new ArrayList(); params2.add(new BasicNameValuePair("email", setting.getID())); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params2, HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePost = client.execute(post); HttpEntity resEntity = responsePost.getEntity(); if (resEntity != null) { resp = EntityUtils.toString(resEntity); } } catch (Exception e) { e.printStackTrace(); } return null; }
/** ジョブの設定内容を置き換える。 */ private void replaceJobSetting(String dstJob) throws Exception { LOGGER.info("[start] replaceJobSetting"); // Getリクエスト送信 String requestUrl = hudsonUrl + "job" + "/" + dstJob + "/" + "config.xml"; HttpGet getRequest = new HttpGet(requestUrl); HttpResponse getResponse = client.execute(getRequest); // Getレスポンス取得 LOGGER.info(getResponse.getStatusLine()); LOGGER.info("get job setting '" + dstJob + "'"); String config = EntityUtils.toString(getResponse.getEntity()); getResponse.getEntity().consumeContent(); // 文字列置換 String replacedConfig = config.replaceAll(REPLACE_STRING, dstJob); // Postリクエスト送信 HttpPost postRequest = new HttpPost(requestUrl); postRequest.setEntity(new StringEntity(replacedConfig, HTTP.UTF_8)); HttpResponse postResponse = client.execute(postRequest); // Postレスポンス取得 LOGGER.info(postResponse.getStatusLine()); LOGGER.info("replace job setting '" + dstJob + "'"); postResponse.getEntity().consumeContent(); LOGGER.info("[ end ] replaceJobSetting"); }
@Test public void testUpdatedDataset() throws Exception { Dataset dataset = new Dataset(); dataset.setTitle("Foobar"); Endpoint endpoint = new Endpoint(); endpoint.setUrl(URI.create("http://localhost/nmr")); dataset.addEndpoint(endpoint); when(client.execute(argThat(HttpGetMatcher.matchUrl("http://localhost/nmr?op=capabilities")))) .thenReturn(prepareResponse(200, "tapir/capabilities1.xml")); when(client.execute(argThat(HttpGetMatcher.matchUrl("http://localhost/nmr")))) .thenReturn(prepareResponse(200, "tapir/metadata1.xml")); when(client.execute( argThat( HttpGetMatcher.matchUrl( "http://localhost/nmr?op=s&t=http%3A%2F%2Frs.gbif.org%2Ftemplates%2Ftapir%2Fdwc%2F1.4%2Fsci_name_range.xml&count=true&start=0&limit=1&lower=AAA&upper=zzz")))) .thenReturn(prepareResponse(200, "tapir/search1.xml")); SyncResult syncResult = synchroniser.syncInstallation(installation, Lists.newArrayList(dataset)); assertThat(syncResult.deletedDatasets).describedAs("Deleted datasets").isEmpty(); assertThat(syncResult.existingDatasets).hasSize(1); assertThat(syncResult.addedDatasets).isEmpty(); assertThat(syncResult.existingDatasets.get(dataset).getTitle()) .isEqualTo("ENGLISHNatural History Museum Rotterdam"); }
private String fetchStringData( final String url, final Map<String, String> requestParams, final RequestType requestType) throws IOException { Ln.d("Making %s request to %s.", requestType, url); if (requestType == RequestType.GET) { final StringBuilder realUrl = new StringBuilder(); realUrl.append(url); if (!requestParams.isEmpty()) { realUrl.append("?"); for (String key : requestParams.keySet()) { realUrl.append(key); realUrl.append("="); realUrl.append(URLEncoder.encode(requestParams.get(key), "UTF-8")); } } return httpClient.execute(new HttpGet(realUrl.toString()), new BasicResponseHandler()); } else if (requestType == RequestType.POST) { final HttpPost httpPost = new HttpPost(url); final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String key : requestParams.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, requestParams.get(key))); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); return httpClient.execute(httpPost, new BasicResponseHandler()); } else { throw new IllegalStateException("Invalid HTTP request type."); } }
// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public static final String upLoadPic2Server(String picPath, String board, Context context) throws IOException { if (picPath == null || picPath.length() == 0) { return ""; } LoginInfo loginInfo = LoginInfo.getInstance(context); File file = new File(compressBitmapByPath(picPath)); HttpClient client; BasicHttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 10000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); client = new DefaultHttpClient(httpParameters); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String url = "http://bbs.nju.edu.cn/" + loginInfo.getLoginCode() + "/bbsdoupload?ptext=text&board=" + board; HttpPost imgPost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("up", new FileBody(file)); reqEntity.addPart("exp", new StringBody("", Charset.forName("GB2312"))); reqEntity.addPart("ptext", new StringBody("text", Charset.forName("GB2312"))); reqEntity.addPart("board", new StringBody(board, Charset.forName("GB2312"))); imgPost.setEntity(reqEntity); imgPost.addHeader("Cookie", loginInfo.getLoginCookie()); imgPost.addHeader(reqEntity.getContentType()); String result; HttpResponse httpResponse; httpResponse = client.execute(imgPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(httpResponse.getEntity()); result = result.substring(result.indexOf("url=") + 2, result.indexOf(">") - 1); String fileNum = result.substring(result.indexOf("file=") + 5, result.indexOf("&name")); String fileName = file.getName(); if (fileName.length() > 10) { fileName = fileName.substring(fileName.length() - 10); } url = "http://bbs.nju.edu.cn/" + loginInfo.getLoginCode() + "/bbsupload2?board=" + board + "&file=" + fileNum + "&name=" + fileName + "&exp=&ptext=text"; HttpGet uploadGet = new HttpGet(url); uploadGet.addHeader("Cookie", loginInfo.getLoginCookie()); httpResponse = client.execute(uploadGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString(httpResponse.getEntity()); return result.substring(result.indexOf("'\\n") + 3, result.indexOf("\\n'")); } } return null; }
@Override protected Integer doInBackground(String... arg0) { // TODO Auto-generated method stub Log.i("BackActivity", "backInfoAccess doInBackground..."); String ID = arg0[0]; BasicNameValuePair pair1 = new BasicNameValuePair("Log_username", ID); List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(pair1); if (parameters != null) { HttpClient client = new DefaultHttpClient(); UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8); HttpPost post = new HttpPost(ConUtils.backInfo_url); post.setEntity(entity); client.execute(post); HttpResponse response = client.execute(post); HttpEntity resultEntity = response.getEntity(); // Log.i("BackActivity", ); // InputStream in = response.getEntity().getContent();//服务器返回的数据 // int code = response.getStatusLine().getStatusCode(); if (resultEntity != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resultEntity.getContent(), "utf-8")); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); JSON json = new JSON(); String key[] = new String[2]; String result[]; key[0] = "success"; key[1] = "activity"; result = json.getJSON(sb.toString(), key); // in.toString(); if (result == null) { result = new String[1]; result[0] = "结果为空"; } for (int i = 0; i < result.length; i++) { Log.i("BackActivity", "string " + result[i]); } } // Log.i("BackActivity", in.toString()); Log.i("BackActivity", "backInfoAccess success!"); return 1; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }
@Override protected Boolean doInBackground(final String... fileNames) { final int n = fileNames.length / 3; for (i = 0; i < fileNames.length - 1; i = i + 3) { HttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); String url = this.UPLOAD_URL + "?FileName=" + URLEncoder.encode(fileNames[i]) + "&BlobId=" + URLEncoder.encode(fileNames[i + 2]) + "&EntityName=t_blob"; HttpPost httpPost = new HttpPost(url); try { CountableFileEntity entity = new CountableFileEntity( new File(fileNames[i]), "binary/octet-stream", new ProgressListener() { @Override public void transferred(long num) { ProgressIndicator idc = new ProgressIndicator(); idc.progress = (int) ((100.0 * i / 3 / n) + (num / (float) totalSize) * 100 / n); idc.hint = "上传文件:" + fileNames[i + 1]; publishProgress(idc); } }); totalSize = entity.getContentLength(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost, httpContext); response.getEntity(); } catch (Exception e) { return false; } } HttpPost httpPost = new HttpPost(Vault.IIS_URL + "update"); try { httpPost.setEntity(new StringEntity(fileNames[fileNames.length - 1], "UTF8")); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(), "UTF8"); JSONObject obj = new JSONObject(result); if (obj.getString("ok").equals("nok")) return false; else return true; } catch (Exception e) { ProgressIndicator idc = new ProgressIndicator(); idc.progress = 100; idc.hint = "上传安检记录出错!"; publishProgress(idc); return false; } }
@Override protected String doInBackground(String... urls) { HttpClient httpClient = new DefaultHttpClient(); Log.d("inbgactivity", urls[0]); if (networkStatus() == NETWORK_STATUS_OK) { if (method.equalsIgnoreCase("POST")) { try { HttpPost request = new HttpPost(urls[0]); Log.d("asd", this.params); StringEntity parameters = new StringEntity(params); request.addHeader("content-type", "application/json"); request.setEntity(parameters); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("GET")) { try { HttpGet request = new HttpGet(urls[0]); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else if (method.equalsIgnoreCase("OAUTH_GET")) { try { OAuthConsumer consumer = new DefaultOAuthConsumer(LINKEDIN_API_KEY, LINKEDIN_SECRET_KEY); consumer.setTokenWithSecret(urls[1], urls[2]); URL url = new URL(urls[0]); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setRequestMethod("GET"); request.setUseCaches(true); consumer.sign(request); request.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d("as", sb.toString()); return sb.toString(); } catch (Exception e) { e.printStackTrace(); Log.d("bg exception", e.toString()); return null; } } else return null; } else { return null; } }
@Test public void testOneRequestSimpleFailover( @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { HttpClient client = HttpClients.createDefault(); URI uri1 = SimpleServlet.createURI(baseURL1); URI uri2 = SimpleServlet.createURI(baseURL2); try { HttpResponse response = client.execute(new HttpGet(uri1)); try { log.info( "Requested " + uri1 + ", got " + response.getFirstHeader("value").getValue() + "."); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Now check on the 2nd server response = client.execute(new HttpGet(uri2)); try { log.info( "Requested " + uri2 + ", got " + response.getFirstHeader("value").getValue() + "."); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals( "Session failed to replicate after container 1 was shutdown.", 2, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // and back on the 1st server response = client.execute(new HttpGet(uri1)); try { log.info( "Requested " + uri1 + ", got " + response.getFirstHeader("value").getValue() + "."); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals( "Session failed to replicate after container 1 was brough up.", 3, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }
/** * This method sends a login POST request to ensure the authentication and then send the POST * request with the action needed */ public String loginAndExecuteBuilder( String URI_LOGIN, String URI_ACTION, List<NameValuePair> nameValuePairsLogin, List<NameValuePair> nameValuePairsAction) { String result = new String(); HttpPost httppost; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response, response_action; HttpEntity entity, entity_action; try { httppost = new HttpPost(URI_LOGIN); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsLogin)); response = httpclient.execute(httppost); entity = response.getEntity(); entity.getContent(); entity.consumeContent(); httppost = new HttpPost(URI_ACTION); // Url Encoding the POST parameters try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsAction)); } catch (UnsupportedEncodingException e) { // writing error to Log Log.v( "NetworkTools", "Exception executing POST: " + URI_ACTION + " Exception: " + e.toString()); } // Log.v("Interoperabilty","URI para buscar " + buildHttpHostRequest(URI_ACTION, // convertStreamToString(httppost.getEntity().getContent()))); HttpPost httppost_p = new HttpPost( buildHttpHostRequest( URI_ACTION, convertStreamToString(httppost.getEntity().getContent()))); response_action = httpclient.execute(httppost_p); entity_action = response_action.getEntity(); if (entity_action != null) { result = new String(); result = convertStreamToString(response_action); entity_action.consumeContent(); } } catch (Exception e) { Log.v( "NetworkTools", "Exception in POST request: " + URI_ACTION + " Exception: " + e.toString()); return ""; } return result; }
// function to do the compute use case public static void compute() throws Exception { HttpPost method = new HttpPost(url + "/compute"); method.setEntity(new StringEntity(username, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } System.out.println("Give the file name which has to be put in the grid for computation"); // input of the file name to be computed BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.readLine(); // get the absolute path of the current working directory File directory = new File("."); String pwd = directory.getAbsolutePath(); // get present time date = new Date(); long start = date.getTime(); String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp; System.out.println(cmd); // Execute the vishwa compute process Process p = Runtime.getRuntime().exec(cmd); // wait till the compute process is completed // check for the status code (0 for successful termination) int status = p.waitFor(); if (status == 0) { System.out.println("Compute operation successful. Check the directory for results"); } date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/computeAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
@Override protected String doInBackground(String... params) { String urlString = params[0]; String urlMethod = "GET"; String payload = null; if (params.length > 1) { urlMethod = params[1]; } if (params.length > 2) { payload = params[2]; } HttpResponse response = null; String resultToDisplay = ""; InputStream in = null; HttpClient httpClient = new DefaultHttpClient(); try { if (urlMethod == "POST" && payload != null) { HttpPost httpPost = new HttpPost(urlString); StringEntity entity = new StringEntity(payload); entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding( new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); httpPost.setEntity(entity); response = httpClient.execute(httpPost); } else if (urlMethod == "PUT" && payload != null) { HttpPut httpPut = new HttpPut(urlString); StringEntity entity = new StringEntity(payload); entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding( new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); httpPut.setEntity(entity); response = httpClient.execute(httpPut); } else if (urlMethod == "DELETE") { HttpDelete httpDelete = new HttpDelete(urlString); response = httpClient.execute(httpDelete); } else if (urlMethod == "GET") { HttpGet httpGet = new HttpGet(urlString); response = httpClient.execute(httpGet); } if (response != null) { in = response.getEntity().getContent(); resultToDisplay = convertStreamToString(in); } } catch (UnsupportedEncodingException e) { resultToDisplay = ""; } catch (ClientProtocolException e) { resultToDisplay = ""; } catch (IOException e) { resultToDisplay = ""; } return resultToDisplay; }
protected String getData( String url, String method, String contentType, String content, ContinuationToken cTokens) { try { HttpClient client = new DefaultHttpClient(); HttpResponse res = null; url = url.replaceAll(" ", "%20"); if (method == "GET") { HttpGet get = new HttpGet(url); get.addHeader("Authorization", token); get.addHeader("Content-Type", contentType); get.addHeader("Content-Length", content.length() + ""); res = client.execute(get); } else if (method == "POST") { HttpPost post = new HttpPost(url); post.addHeader("Authorization", token); post.addHeader("Content-Type", contentType); StringEntity entity = new StringEntity(content, HTTP.UTF_8); post.setEntity(entity); res = client.execute(post); } else if (method == "DELETE") { HttpDelete del = new HttpDelete(url); del.addHeader("Authorization", token); del.addHeader("Content-Type", contentType); res = client.execute(del); } else if (method == "PUT") { HttpPut put = new HttpPut(url); put.addHeader("Authorization", token); put.addHeader("Content-Type", contentType); StringEntity entity = new StringEntity(content, HTTP.UTF_8); put.setEntity(entity); res = client.execute(put); } StatusLine sl = res.getStatusLine(); String json = ""; if (sl.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); res.getEntity().writeTo(out); out.close(); json = out.toString(); Log.i("result", json); return json; } else { Log.i("error", sl.getReasonPhrase()); } } catch (IOException ex) { ex.printStackTrace(); } return null; }
private HttpResponse doResponse(String url) { // Use our connection and data timeouts as parameters for our // DefaultHttpClient HttpClient httpclient = new DefaultHttpClient(getHttpParams()); ServiceHandler sh = new ServiceHandler(); try { httpclient.getConnectionManager().getSchemeRegistry().register(sh.getMockedScheme()); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpResponse response = null; try { switch (taskType) { case POST_TASK: HttpPost httppost = new HttpPost(url); // Add parameters httppost.setEntity(new UrlEncodedFormEntity(params)); response = httpclient.execute(httppost); break; case GET_TASK: HttpGet httpget = new HttpGet(url); httpget.setHeader( "Authorization", "Bearer pOuJzg0Y0FtJpO-Ugson2P_8dbmvaDiBZs7Z-v_2eIgGgUfFsiWS-TOIkNlquCQGHuu3OyeWCFVIB7xJjEp6nKg9iY1-gzRfjHtdvBk7MVemtm6Ksf5AmmKmuZleLR_-bNMorwUOqTs0BCjAomM6h2peaXA3LTJ_-V6CDpnKVmmfTf0DvVQYBsbtLG94sSAGUToxjhw9GQhkukkSLvMIYMRKt-R5M2walOq63_eJx17y7HQxlxjOffR41wq4sANewOFlIOuf2czn2QP_FuVg_2SwUpeQctMGYwSgLC7H2gUPFtWzSWB9AhG4Pfwfmy0cd4mxZrrPBglehg8_VpK0pzXpEDMYJ-mBtpZOkAaTXSr0f8aw8Y2CMCmLgRUtC5_JA9NtLhJ6TEBDeNco8Fj6ZfMyZEDxB6xg3MD0fgs7fkbqSUGj4bV54DbvrniSKQ9GwZM29tHXI1xzrvnTg0NIg1ul4kOSWiVeW88-PUlUTXA9kzKsE20CL_CrbOJUlaFhSYHMz-KAisKgtUynMe0lUg"); // response.setHeader("Authorization", // "Bearer // pOuJzg0Y0FtJpO-Ugson2P_8dbmvaDiBZs7Z-v_2eIgGgUfFsiWS-TOIkNlquCQGHuu3OyeWCFVIB7xJjEp6nKg9iY1-gzRfjHtdvBk7MVemtm6Ksf5AmmKmuZleLR_-bNMorwUOqTs0BCjAomM6h2peaXA3LTJ_-V6CDpnKVmmfTf0DvVQYBsbtLG94sSAGUToxjhw9GQhkukkSLvMIYMRKt-R5M2walOq63_eJx17y7HQxlxjOffR41wq4sANewOFlIOuf2czn2QP_FuVg_2SwUpeQctMGYwSgLC7H2gUPFtWzSWB9AhG4Pfwfmy0cd4mxZrrPBglehg8_VpK0pzXpEDMYJ-mBtpZOkAaTXSr0f8aw8Y2CMCmLgRUtC5_JA9NtLhJ6TEBDeNco8Fj6ZfMyZEDxB6xg3MD0fgs7fkbqSUGj4bV54DbvrniSKQ9GwZM29tHXI1xzrvnTg0NIg1ul4kOSWiVeW88-PUlUTXA9kzKsE20CL_CrbOJUlaFhSYHMz-KAisKgtUynMe0lUg"); // httpget.addHeader("Authorization", // "Bearer // pOuJzg0Y0FtJpO-Ugson2P_8dbmvaDiBZs7Z-v_2eIgGgUfFsiWS-TOIkNlquCQGHuu3OyeWCFVIB7xJjEp6nKg9iY1-gzRfjHtdvBk7MVemtm6Ksf5AmmKmuZleLR_-bNMorwUOqTs0BCjAomM6h2peaXA3LTJ_-V6CDpnKVmmfTf0DvVQYBsbtLG94sSAGUToxjhw9GQhkukkSLvMIYMRKt-R5M2walOq63_eJx17y7HQxlxjOffR41wq4sANewOFlIOuf2czn2QP_FuVg_2SwUpeQctMGYwSgLC7H2gUPFtWzSWB9AhG4Pfwfmy0cd4mxZrrPBglehg8_VpK0pzXpEDMYJ-mBtpZOkAaTXSr0f8aw8Y2CMCmLgRUtC5_JA9NtLhJ6TEBDeNco8Fj6ZfMyZEDxB6xg3MD0fgs7fkbqSUGj4bV54DbvrniSKQ9GwZM29tHXI1xzrvnTg0NIg1ul4kOSWiVeW88-PUlUTXA9kzKsE20CL_CrbOJUlaFhSYHMz-KAisKgtUynMe0lUg"); Client client = new Client(); // response = client. response = httpclient.execute(httpget); // response.addHeader("Authorization", // "Bearer // pOuJzg0Y0FtJpO-Ugson2P_8dbmvaDiBZs7Z-v_2eIgGgUfFsiWS-TOIkNlquCQGHuu3OyeWCFVIB7xJjEp6nKg9iY1-gzRfjHtdvBk7MVemtm6Ksf5AmmKmuZleLR_-bNMorwUOqTs0BCjAomM6h2peaXA3LTJ_-V6CDpnKVmmfTf0DvVQYBsbtLG94sSAGUToxjhw9GQhkukkSLvMIYMRKt-R5M2walOq63_eJx17y7HQxlxjOffR41wq4sANewOFlIOuf2czn2QP_FuVg_2SwUpeQctMGYwSgLC7H2gUPFtWzSWB9AhG4Pfwfmy0cd4mxZrrPBglehg8_VpK0pzXpEDMYJ-mBtpZOkAaTXSr0f8aw8Y2CMCmLgRUtC5_JA9NtLhJ6TEBDeNco8Fj6ZfMyZEDxB6xg3MD0fgs7fkbqSUGj4bV54DbvrniSKQ9GwZM29tHXI1xzrvnTg0NIg1ul4kOSWiVeW88-PUlUTXA9kzKsE20CL_CrbOJUlaFhSYHMz-KAisKgtUynMe0lUg"); break; } } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage(), e); } return response; }
/** * Send post to URL with parameters by given encoding. * * @param url * @param parameterMap * @param encoding * @return */ public static String sendPost( String url, Map<String, String> parameterMap, String encoding, String ip, boolean isBasicResHandler) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); if (ip != null) { httpPost.setHeader("X-Forwarded-For", ip); } // httpPost.setHeader("Host", "api.xueqiu.com"); if (parameterMap != null && !parameterMap.isEmpty()) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Iterator<Map.Entry<String, String>> it = parameterMap.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, String> entry = it.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { if (encoding == null) { httpPost.setEntity(new UrlEncodedFormEntity(params)); } else { httpPost.setEntity(new UrlEncodedFormEntity(params, encoding)); } } catch (UnsupportedEncodingException e) { log.error("Encode the parameter failed!", e); } } String content = null; try { if (url.indexOf("https") != -1) { httpClient = wrapClient(httpClient); } if (isBasicResHandler) { content = httpClient.execute(httpPost, new BasicResponseHandler()); } else { HttpResponse httpresponse = httpClient.execute(httpPost); content = EntityUtils.toString(httpresponse.getEntity()); } } catch (Exception e) { log.error("Get url faild, url: " + url, e); content = null; } finally { httpClient.getConnectionManager().shutdown(); } return content; }
public void executar() { try { UrlEncodedFormEntity urlParametros = new UrlEncodedFormEntity(parametros, HTTP.UTF_8); Log.d("erro2", tipo); if (tipo.equalsIgnoreCase("POST")) { post.setEntity(urlParametros); resposta = cliente.execute(post); } else { resposta = cliente.execute(get); } } catch (Exception e) { Log.d("cod", e.toString()); resposta = null; } }
private String getListOrdersResponse() throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(baseUri); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); return getResponseString(entity); }
public JSONArray getUserTimezoneHistory( UpdateInfo updateInfo, String api_key, OAuthConsumer consumer) throws Exception { long then = System.currentTimeMillis(); String requestUrl = "http://api.bodymedia.com/v2/json/timezone?api_key=" + api_key; HttpGet request = new HttpGet(requestUrl); consumer.sign(request); HttpClient client = env.getHttpClient(); enforceRateLimits(getRateDelay(updateInfo)); HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); final String reasonPhrase = response.getStatusLine().getReasonPhrase(); if (statusCode == 200) { countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String json = responseHandler.handleResponse(response); JSONObject userInfo = JSONObject.fromObject(json); return userInfo.getJSONArray("timezones"); } else { countFailedApiCall( updateInfo.apiKey, updateInfo.objectTypes, then, requestUrl, "", statusCode, reasonPhrase); throw new Exception( "Error: " + statusCode + " Unexpected error trying to bodymedia timezone for user " + updateInfo.apiKey.getGuestId()); } }
@Test public void testMultipart() throws IOException, JSONException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/"); File image = new File("resources/test/base.png"); FileBody imagePart = new FileBody(image); StringBody messagePart = new StringBody("some message"); MultipartEntity req = new MultipartEntity(); req.addPart("image", imagePart); req.addPart("message", messagePart); httppost.setEntity(req); ImageEchoServer server = new ImageEchoServer(PORT); HttpResponse response = httpclient.execute(httppost); server.stop(); HttpEntity resp = response.getEntity(); assertThat(resp.getContentType().getValue(), is("application/json")); // sweet one-liner to convert an inputstream to a string from stackoverflow: // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string String out = new Scanner(resp.getContent()).useDelimiter("\\A").next(); JSONObject json = new JSONObject(out); String base64 = Base64.encodeFromFile("resources/test/base.png"); assertThat(json.getString("screenshot"), is(base64)); assertThat(json.getBoolean("imageEcho"), is(true)); }
@Override protected String doInBackground(String... params) { // TODO Auto-generated method stub try { StringEntity se; // Log.e("http string",URL+"//"+send.toString()); HttpParams httpParameters = new BasicHttpParams(); // set connection parameters HttpConnectionParams.setConnectionTimeout(httpParameters, 60000); HttpConnectionParams.setSoTimeout(httpParameters, 60000); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpResponse response = null; HttpPost httppost = new HttpPost(params[0]); httppost.setHeader("Content-type", "application/json"); se = new StringEntity(params[1]); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); streamtostring(is); } catch (Exception e) { e.printStackTrace(); } return null; }
@Override public Boolean doInBackground(String... urls) { try { // ------------------>> HttpGet httppost = new HttpGet(urls[0]); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); Log.e("status", status + ""); if (status == 200) { HttpEntity entity = response.getEntity(); data = EntityUtils.toString(entity); return true; } // ------------------>> } catch (IOException e) { e.printStackTrace(); } return false; }
/** * Get the user preferences from the GPII * * @param user * @return * @throws Exception */ private String getPreferencesFromServer(EasitAccount user) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet( environment.getProperty("flowManager.url") + environment.getProperty("flowManager.preferences")); // add the access token to the request header request.addHeader("Authorization", "Bearer " + user.getAccessToken()); HttpResponse response = client.execute(request); // NOT Correct answer if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Correct answer BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } logger.info("User preferences:" + result); return result.toString(); }
@Test public void testServerReturnsWrongVersionForDstu2() throws Exception { Conformance conf = new Conformance(); conf.setFhirVersion("0.80"); String msg = myCtx.newXmlParser().encodeResourceToString(conf); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpResponse.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); when(myHttpResponse.getEntity().getContentType()) .thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); when(myHttpResponse.getEntity().getContent()) .thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); try { myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123")); fail(); } catch (FhirClientInappropriateForServerException e) { String out = e.toString(); String want = "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2 (via the FhirContext)"; ourLog.info(out); ourLog.info(want); assertThat(out, containsString(want)); } }
@Test public void testServerReturnsAnHttp401() throws Exception { ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpResponse.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized")); when(myHttpResponse.getEntity().getContentType()) .thenReturn(new BasicHeader("content-type", Constants.CT_TEXT)); when(myHttpResponse.getEntity().getContent()) .thenAnswer( new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock theInvocation) throws Throwable { return new ReaderInputStream( new StringReader("Unauthorized"), Charset.forName("UTF-8")); } }); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); IGenericClient client = myCtx.newRestfulGenericClient("http://foo"); try { client.read().resource(Patient.class).withId("123").execute(); fail(); } catch (AuthenticationException e) { // good } }
@Test public void testGetAndCheckKey() throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://*****:*****@gmail.com")); nvps.add(new BasicNameValuePair("password", "Purbrick7")); post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(post); assertEquals(200, response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); String responseContent = IOUtils.toString(entity.getContent()); System.out.println(response.getFirstHeader("Content-Type")); System.out.println(responseContent); JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseContent); HttpPost post2 = new HttpPost("http://*****:*****@gmail.com")); nvps2.add(new BasicNameValuePair("authKey", (String) jsonObj.get("authKey"))); post2.setEntity(new UrlEncodedFormEntity(nvps2, HTTP.UTF_8)); HttpResponse response2 = httpClient.execute(post2); assertEquals(200, response2.getStatusLine().getStatusCode()); }