Hi i use linux and when i try to import the following packages compilation is giving error.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import com.google.gson.Gson;
How can i install these packages in my linux and then compile. My code as follows,
class pojo1
{
String name=abc;
String age=18;
//generate setter and getters
}
public class SimpleURL
{
public static void main(String[] args)
{
String postUrl="www.site.com";// put in your url
Gson gson= new Gson();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//convert your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type","application/json");
HttpResponse response = httpClient.execute(post);
}
}
Try
javac -cp .;httpclient.jar MyClass.java
java -cp .;httpclient.jar MyClass
Related
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import javax.swing.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.sql.Driver;
import java.time.Duration;
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demoqa.com/");
driver.manage().window().maximize();
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://demoqa.com/");
HttpResponse response = client.execute(request);
int statusCode = response.statusCode();
System.out.println(statusCode);
hi,
first of all, my first question is when I create the client object with HttpClient, for HttpClient
it throws an error and says "Required type:
HttpClient
Provided:
It gives a warning like "CloseableHttpClient".
Secondly
The execute method in HttpClient is not working.
Can you help me ?
You're mixing apples with pears, org.apache.http with java.net.http.
Maven dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Code sample:
package tests;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpClientTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://demoqa.com/");
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine());
System.out.println(response.getStatusLine().getStatusCode());
}
}
Output:
HTTP/1.1 200 OK
200
I am running an application on tomcat server. I am getting following error while callling a specific function :
java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy
My class is :
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
/*import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;*/
//import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.performics.air.business.common.data.HttpParam;
public class SendAndReceiveUtil implements Serializable {
//FIXME: move to suitable package
/**
*
*/
private static final long serialVersionUID = 2649891233958197253L;
private static Logger LOG = Logger.getLogger(SendAndReceiveUtil.class);
public static String httpPostWithTLS(String request,String url,Map<String,String> headerParameterMap){
String responseStr = null;
try{
// FIXME: need to handle supplier timeout and gzip
String contentType="";
String soapAction="";
boolean zipForRequest=false;
boolean acceptEncoding = false;
boolean zipForResponse=false;
if (headerParameterMap!=null){
contentType=headerParameterMap.get(HttpParam.CONTENTTYPE.toString())!=null?headerParameterMap.get(HttpParam.CONTENTTYPE.toString()):"";
zipForRequest=(headerParameterMap.containsKey(HttpParam.ZIPFORREQUEST.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORREQUEST.toString())):false;
acceptEncoding=(headerParameterMap.containsKey(HttpParam.ACCEPT_ENCODING.toString()))? new Boolean(headerParameterMap.get(HttpParam.ACCEPT_ENCODING.toString())):false;
zipForResponse=(headerParameterMap.containsKey(HttpParam.ZIPFORRESPONSE.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORRESPONSE.toString())):false;
soapAction=headerParameterMap.get(HttpParam.SOAPACTION.toString())!=null?headerParameterMap.get(HttpParam.SOAPACTION.toString()):"";
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build();
// Allow TLSv1.2 protocol only, use NoopHostnameVerifier to trust self-singed cert
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1.2" }, null, new NoopHostnameVerifier());
//do not set connection manager
HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("SOAPAction", soapAction);
StringEntity mEntity = new StringEntity(request, "UTF-8");
if(StringUtils.isNotBlank(contentType)){
mEntity.setContentType(contentType);
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,contentType));
}else{
mEntity.setContentType("text/xml;charset=UTF-8");
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,"gzip"));
}
httpPost.addHeader("Content-Encoding", "gzip" );
httpPost.addHeader("Accept-Encoding", "gzip,deflate" );
if(null!=headerParameterMap.get("Cookie")){
httpPost.addHeader("Cookie", headerParameterMap.get("Cookie"));
}
httpPost.setEntity(mEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity et=response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
et.writeTo(os);
responseStr = new String(os.toByteArray());
}catch(Exception e){
LOG.error(e.getMessage(), e);
}
return responseStr;
}
}
Error comes on calling httpPostWithTLS() function. I searched about it on net and found that class was available at compile but is not available at run time, but i am unable to correct it.
I am using following http jars:
commons-httpclient-3.1.jar
httpclient-4.5.3.jar
httpcore-4.4.6.jar
httpclient-cache-4.5.3.jar
httpclient-win-4.5.3.jar
httpmime-4.5.3.jar
Try to add the httpcore-4.4.6.jar and httpclient-cache-4.5.3.jar to server library and check.
I do face the similar issue after adding these jar file, my problem is resolved.
Thanks,
I am retrieving URL from database and it contains special characters like % - = / ? etc. so while I try to populate that in my page JSON is not able to parse that URL and it is giving me some exception when I was debugging I got like this
(Log4JLogger.java:log:449) [SECURITY FAILURE Anonymous:null#unknown -> /ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected
I tried from these link here this my offending URL here
but it is not working he mentioned that bug is solved. but for which version version here I am using is 2.1.0 below is my code
package com.ghn.repufact.review.extractor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.log4j.Logger;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultValidator;
import org.springframework.stereotype.Component;
#Component
public class ValidateURL {
private static final Logger logger=Logger.getLogger(ValidateResponse.class);
public String parseOrgConsumerLink(String myLink) throws URISyntaxException {
if(myLink==null || "".equalsIgnoreCase(myLink))
return myLink;
Encoder enc=ESAPI.encoder();
URI mixURI=new URI(myLink);
UriBuilder uriBuider=UriBuilder.fromUri(enc.canonicalize(mixURI.getAuthority()+mixURI.getPath()));
uriBuider.path(enc.canonicalize(mixURI.getAuthority() + mixURI.getPath()));
logger.info("Uri after URIbuilder:"+uriBuider.build().toString());
List<NameValuePair> params = URLEncodedUtils.parse(mixURI, "UTF-8");
for (NameValuePair nameValuePair : params)
uriBuider.queryParam(enc.canonicalize(nameValuePair.getName()), enc.canonicalize(nameValuePair.getValue()));
String canonicalizedUrl = uriBuider.build().toString();
logger.info("canonicaliz URI:"+canonicalizedUrl);
return canonicalizedUrl;
}
public boolean isCanonicalizedURI(String myLink) throws EncodingException {
Validator validator=DefaultValidator.getInstance();
//boolean flag=validator.isValidInput("test", myLink, "URI", 200, false);
myLink = ESAPI.encoder().encodeForURL(myLink);
boolean flag = validator.isValidInput("APPNAME", myLink, "URLSTRING", 600, true, false);
logger.info("checking for URI:"+myLink+" isCanonical:"+flag);
return flag;
}
}
please let me know if any work around here. By the way I am using spring MVC
Executing this url on my browser: http://localhost:3161/devices/simulator/stop
I don't need login for it. It returns this rest api xml:
<response>
<type>response</type>
<ts>1463749194000</ts>
<status>OK</status>
<msg-version>2.3.0</msg-version>
<op>stop</op>
<data/>
</response>
How can I execute this from JAVA and then capture the xml response?
As other mentioned in this post, it is generic thing, you would be able to find it online already..
I know there are clients to call the REST services from Java. Two of them are listed for your case.
case -1 : if you are using Jersey REST API. Here to capture XML , you can go with your own way,for example use JAXB and XML elements to Java Bean properties.
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(UriBuilder.fromUri('http://localhost:3161/devices/simulator/stop').build());
// getting XML data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_JSON).get(String.class));
// getting JSON data
System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class));
}
}
Case 2: using HTTP method, it is simple method but parse XML instead of printing it here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet('http://localhost:3161/devices/simulator/stop');
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = '';
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}
Hello I have a class for doing webdav related operations such as creating a directory, Implementatiion can be seen below (the createDir method). The question is how to test it nicely, perhaps using EasyMock or a similar lib. Any ideas? thanks!
package foobar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mypackage.httpdclient.util.URLHandler;
public class WebDavImpl{
private static final String SEPARATOR = " ----- ";
private HttpClient httpClient;
public StorageSpaceClientImpl() {
httpClient = new HttpClient();
}
public String createDir(String dirName) {
String response = null;
String url = URLHandler.getInstance().getDirectoryUrl(dirName);
DavMethod mkcol = new MkColMethod(url);
try {
httpClient.executeMethod(mkcol);
response = mkcol.getStatusCode() + SEPARATOR + mkcol.getStatusText();
} catch (IOException ex) {
} finally {
mkcol.releaseConnection();
}
return response;
}
}