I unable to use put method to send data to particular link.. Please find below the code.Let me know if i have to make any change
public class test {
private static String url = "http://semldvw0728.google.net/.svc/web/testrequests/";
private static String urlconnection;
public static void main(String[] args) throws IOException {
StringBuffer xmlString = new StringBuffer();
xmlString.append("<TestRequest>");
xmlString.append("<DateRequested>2011-12-20</DateRequested>");
xmlString.append("<DemCapID>893467</DemCapID>");
xmlString.append("<DemCapVersion>1</DemCapVersion>");
xmlString.append("<IBIS_ID>13530</IBIS_ID>");
xmlString.append("<ProjectName>LTS</ProjectName>");
xmlString.append("<RequestedBy>ktmq331</RequestedBy>");
xmlString.append("<SampleNumber>SN1033645061</SampleNumber>");
xmlString.append("<Status>Sample Ordered</Status>");
xmlString.append("</TestRequest>");
System.out.println("xmlString :" + xmlString.toString());
url = url + 893467;
System.out.println("URL : " + url);
try {
System.out.println("URL : " + url);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
client.setConnectionTimeout(8000);
putMethod.setRequestBody(xmlString.toString());
System.out.println("statusLine>>>" + putMethod.getStatusLine());
System.out.println("statusLine>>>"+ putMethod.getResponseBodyAsString());
putMethod.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to make a call to execute, or you could use the HttpClient object you've created to call this.
So maybe add this line after you're setting the request body for your putMethod...
client.executMethod(putMethod);
Related
I have a test class in which the maine executes code in which I get test data that I have to use in my test, how to make the maine method run first, and then the rest of the code in the class. If I run the class through testng.xml then the main method doesn’t even start at all. And if I run main, the rest of the code just doesn’t start either
package testClassPackage;
public class testWeatherChrome {
public static String parcedData;
public static void main(String[] args) throws IOException {
String sURL = "http://api.openweathermap.org/data/2.5/forecast/?q=Odessa,ua&APPID=518a64dd48106aa542464d3bd94d12ce"; //just a string
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
JsonArray message = rootobj.get("list").getAsJsonArray();
Map<String, String> data = new TreeMap<>();
for (JsonElement lst : message) {
JsonObject lstObject = lst.getAsJsonObject();
JsonObject el = (JsonObject) lstObject.get("main");
// System.out.println(lstObject.get("dt_txt").getAsString() + " " + el.get("temp").getAsString());
if (lstObject.get("dt_txt").getAsString().contains(" 12")) {
data.put("Дата " + lstObject.get("dt_txt").getAsString(), "Прогноз День:" + el.get("temp").getAsString());
} else if (lstObject.get("dt_txt").getAsString().contains(" 21")) {
data.put("Дата " + lstObject.get("dt_txt").getAsString(), "Прогноз Ночь:" + el.get("temp").getAsString());
}
}
Gson gson = new Gson();
Type gsonType = new TypeToken<TreeMap>() {
}.getType();
String gsonData = gson.toJson(data, gsonType);
parcedData = gsonData;
System.out.println("main");
}
#BeforeClass
public void setUp () {
initDriver.getInstance("chrome");
}
#Test
public void getTitle() throws InterruptedException {
String URL ="https://accounts.google.com/signin/v2/identifier?hl=ru&passive=true&continue=https%3A%2F%2Fwww.google.com%2F%3Fgws_rd%3Dssl&flowName=GlifWebSignIn&flowEntry=ServiceLogin";
initDriver.driver.get(URL);
initDriver.driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
initDriver.driver.findElement(By.xpath("//input[#id=\"identifierId\"]")).sendKeys("lesha.test111#gmail.com");
initDriver.driver.findElement(By.xpath("//span[text()=\"Далее\"]")).click();
WebDriverWait wait = new WebDriverWait(initDriver.driver, 10);
WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#type=\"password\"]")));
// initDriver.driver.findElement(By.xpath("//input[#type=\"password\"]")).sendKeys("Leshasugurov222");
passwordElement.sendKeys("Leshasugurov222");
initDriver.driver.findElement(By.xpath("//span[text()=\"Далее\"]")).click();
initDriver.driver.findElement(By.xpath("//a[text()=\"Почта\"]")).click();
initDriver.driver.findElement(By.xpath("//div[text()=\"Написать\"]")).click();
initDriver.driver.findElement(By.xpath("//textarea[#aria-label=\"Кому\"]")).sendKeys("leshaa.test333#gmail.com");
initDriver.driver.findElement(By.xpath("//input[#aria-label=\"Тема\"]")).sendKeys("Погода на неделю для Одессы");
System.out.println(WeatherParse.parcedData);
// initDriver.driver.findElement(By.xpath("//div[#aria-label=\"Тело письма\"]")).sendKeys(WeatherParse.parcedData);
}
// #AfterClass
// public void close() {
// initDriver.quit();
// }
}
If you run the testng.xml, it's obvious that the testng.xml file will not respect the main method (as it was not meant to be).
Solution:
1) Use #BeforeSuite annotation and execute your priority tasks.
2) You can also use your testng.xml file and define your test sequence accordingly.
In my app, I am calling a rest api command via an async task class I have made.
When I pass the string through the async task call like this
apiRequest = new APIRequest();
apiRequest.execute("https:api.my/api/url");
I get "Protocol not found: [Ljava.lang.String;#f51e848? ... ]" where the ... is the rest of my api call.
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL(str + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
With this method, I get the error shown above. However, when I cut the string out of the apiRequest call, and paste it directly into the async task, it works perfectly.
Below, code is working with the cut and paste of the url.
apiRequest = new APIRequest();
apiRequest.execute();
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL("https:api.my/api/url" + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
I want to execute java web service method from android app. My web service method signature looks like:
public String getData(String category) throws Exception
The method returns string and accepts a string as argument.
I have executed the method from google chrome's address bar as:
http://localhost:8080/JsonWebService/services/JsonWebService/getData?category=Marketing
Here getData is the name of the method and Marketing is the argument to that method. From explorer it works fine.
But when I add the same url to android app's httppost request it fails saying wrong number of arguments. My android app code is:
HttpPost post = new HttpPost("http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing");
HttpResponse httpres = httpClient.execute(post);
Please Note: Here 192.168.1.7 is required as I am executing the app directly on the device and hence I am not using localhost.
A non argument method executes correctly from android app also.
But when argument is inserted in the url why it fails saying wrong number of arguments in android app and how it executes correctly in google chrome on PC. Please help... Thanks...
I am adding the code here. My java web service code is as follows:
public class JsonWebService {
#POST
#Path("getData")
public String getData(String category) throws Exception {
JSONObject jsonData = new JSONObject();
String Email = "";
String Name = "";
String receivedCat = "";
boolean status = false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/admindb","root","");
java.sql.PreparedStatement query = con.prepareStatement("SELECT * FROM sample WHERE Category =" + "'" + category + "'" + ";");
ResultSet result = query.executeQuery();
while(result.next()){
receivedCat = result.getString("Category");
Name = result.getString("Name");
Email = result.getString("Email");
}
if(receivedCat.equals(category)){
status = true;
jsonData.put("Name",Name);
jsonData.put("Email", Email);
jsonData.put("status", status);
}
}
catch(Exception e) {
e.printStackTrace();
}
return jsonData.toString();
}
My android client code looks as follows:
btnCategory = (Button)findViewById(R.id.button1);
txtCategory = (EditText)findViewById(R.id.editText1);
gridV = (GridView)findViewById(R.id.gridView1);
txtName = (EditText)findViewById(R.id.editText3);
txtEmail = (EditText)findViewById(R.id.editText2);
btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread netThread = new Thread() {
public void run() {
try {
final JSONObject receivedJson;// = new JSONObject();
String URL = "http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing?";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
receivedJson = new JSONObject(jsonPart);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
txtName.setText(receivedJson.getString("Name"));
txtEmail.setText(receivedJson.getString("Email"));
}
catch(Exception e){
}
}
};
netThread.start();
}
});
}
The problem is in the java client in String URL, which is the string of URL that calls the java web service method. Please help me...
I've a web app which is deployed in tomcat and from this web app, i have to consume a SOAP service which is deployed in Websphere. To access this service, i need to pass LTPA token. I'm very new to websphere, don't know how can i get LTPA token in my web app ? I can't modify the implementation of the app which is deployed in web sphere.
I could acheive this by using HttpBasicAuthentication. Here is the code snippet -
public class TokenHelper {
private static Logger logger = LoggerFactory.getLogger(TokenHelper.class);
private static final int HTTP_TIMEOUT_MILISEC = 100000;
private static String lineSeparator = System.getProperty("line.separator");
#Value("#{'${hostname}'}")
private String hostName;
#Value("#{'${port}'}")
private int port;
#Value("#{'${contextpath}'}")
private String contextPath;
#Value("#{'${isbasicauthentication}'}")
private boolean isBasicAuthentication;
#Value("#{'${username}'}")
private String basicAuthenticationUserName;
#Value("#{'${userpassword}'}")
private String basicAuthenticationPassword;
public Map<String, String> getLtpaToken() throws Exception {
Cookie[] cookies = null;
Protocol protocol = null;
Map<String, String> cookiesMap = new HashMap<String, String>();
GetMethod method = new GetMethod();
HttpClient client = new HttpClient();
method.getParams().setSoTimeout(HTTP_TIMEOUT_MILISEC);
protocol = new Protocol("http", new DefaultProtocolSocketFactory(), getPort());
if (isBasicAuthentication) {
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(getBasicAuthenticationUserName(), getBasicAuthenticationPassword());
client.getState().setCredentials(new AuthScope(getHostName(), getPort(), AuthScope.ANY_REALM), defaultcreds);
}
// Execute request
try {
client.getHostConfiguration().setHost(getHostName(), getPort(), protocol);
method = new GetMethod(getContextPath());
method.setFollowRedirects(true);
logger.info(methodName, "URL to get:" + getContextPath());
// Execute the GET method
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
cookies = client.getState().getCookies();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < cookies.length; j++) {
cookiesMap.put(cookies[j].getName(), cookies[j].getValue());
sb.append("CookieName=" + cookies[j].getName() + lineSeparator);
sb.append("Value=" + cookies[j].getValue() + lineSeparator);
sb.append("Domain=" + cookies[j].getDomain() + lineSeparator);
}
sb.append("Status Text>>>" + HttpStatus.getStatusText(statusCode));
logger.debug("Cookies are: {}" + sb.toString());
method.releaseConnection();
}
} catch (Exception e) {
logger.error("Error while getting LTPA token using HttpBasicAuthentication for URL {}" +e);
throw new RuntimeException("Error while getting LTPA token using HttpBasicAuthentication for URL:" + contextPath, e);
} finally {
// Release current connection to the connection pool once you
// are done
method.releaseConnection();
}
return cookiesMap;
}
I am crawling a page that requires username and password for authentication. And I successfully got the 200 OK response back from the server for that page when I passed my username and password in the code. But it gets stop as soon as it gives the 200 OK response back. It doesn't move forward in to that page after authentication to crawl all those links that are there in that page. And this crawler is taken from http://code.google.com/p/crawler4j/.
This is the code where I am doing the authentication stuff...
public class MyCrawler extends WebCrawler {
Pattern filters = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+ "|png|tiff?|mid|mp2|mp3|mp4" + "|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
List<String> exclusions;
public MyCrawler() {
exclusions = new ArrayList<String>();
//Add here all your exclusions
exclusions.add("http://www.dot.ca.gov/dist11/d11tmc/sdmap/cameras/cameras.html");
}
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
DefaultHttpClient client = null;
try
{
System.out.println("----------------------------------------");
System.out.println("WEB URL:- " +url);
client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
new UsernamePasswordCredentials("test", "test"));
client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
for(String exclusion : exclusions){
if(href.startsWith(exclusion)){
return false;
}
}
if (href.startsWith("http://") || href.startsWith("https://")) {
return true;
}
HttpGet request = new HttpGet(url.toString());
System.out.println("----------------------------------------");
System.out.println("executing request" + request.getRequestLine());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
}
catch(Exception e) {
e.printStackTrace();
}
return false;
}
public void visit(Page page) {
System.out.println("hello");
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
System.out.println("Page:- " +url);
String text = page.getText();
List<WebURL> links = page.getURLs();
int parentDocid = page.getWebURL().getParentDocid();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Text length: " + text.length());
System.out.println("Number of links: " + links.size());
System.out.println("Docid of parent page: " + parentDocid);
}
}
And this is my Controller class
public class Controller {
public static void main(String[] args) throws Exception {
CrawlController controller = new CrawlController("/data/crawl/root");
//And I want to crawl all those links that are there in this password protected page
controller.addSeed("http://search.somehost.com/");
controller.start(MyCrawler.class, 20);
controller.setPolitenessDelay(200);
controller.setMaximumCrawlDepth(2);
}
}
Anything wrong I am doing....
As described in http://code.google.com/p/crawler4j/ the shoudVisit() function should only return true or false. But in your code, this function is also fetching the content of the page which is wrong. The current version of crawler4j (3.0) doesn't support crawling of password-protected pages.