I'm using apache http client library to post a maltipart request on some secure(https) server
httpclient-4.5.13.jar, httpcore-4.4.13.jar, httpmime-4.4.1.jar
below is the sample code:
//creating HttpPost
HttpPost httppost = new HttpPost("some https://url");
httppost.addHeader("Content-Type", "multipart/form-data");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("channel_id", String.valueOf(pushNotificationRequest.getChannelId()));
builder.addTextBody("input_type", pushNotificationRequest.getInputType());
builder.addBinaryBody("csv_file", new ByteArrayInputStream(pushNotificationRequest.getCsvFile()), ContentType.DEFAULT_BINARY, "my-File.csv");
httppost.setEntity(builder.build());
//configuration for disabling the SSL
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).useProtocol("TLSv1.2").build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
//exicuting the httppost
httpClient.execute(httppost);
but in above configuration I'm getting a wired issue when I freshly start the tomcat server (as above code in a part of web-app) and when this code is executed I'm able to connect to server which I'm posting the my request and after second attempt onwards I'm getting a exception
as:
[ org.apache.http.client.ClientProtocolException ] null
org.apache.http.client.ClientProtocolException
I'm not able to understand why it's working when server freshly started and getting exception after subsequent call.
Any help is greatly appreciated.
Related
I was trying to post some data to AWS EC2 rest end-point, from an AWS Lambda. I was getting response "with status code: 406 and with status: Not Acceptable". I tried fixing this, with adding accept headers as below
HttpPost httpPost = new HttpPost(serviceURL);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
httpPost.addHeader(HttpHeaders.ACCEPT, "*/*");
httpPost.addHeader(HttpHeaders.ACCEPT_CHARSET, "*");
httpPost.addHeader(HttpHeaders.ACCEPT_ENCODING, "*");
httpPost.addHeader(HttpHeaders.ACCEPT_LANGUAGE, "*");
httpPost.setEntity( new InputStreamEntity(content, ContentType.APPLICATION_XML) );
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(httpPost);
Am i missing something? Is there anything else that i should be looking into?
Attach exception log please. Are u trying to send this method though any kind of front
I am trying to send a HTTP POST request to a site with a HTTPS proxy.
I am currently doing it like that:
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
HttpPost request = new HttpPost("https://example.com");
HttpHost proxy2 = new HttpHost("proxy ip here", 8080, "https");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy2)
.build();
request.setConfig(config);
String json = "\"" + username + "\"";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
CloseableHttpResponse response = httpclient.execute(request, context);
HttpEntity entityresponse = response.getEntity();
responseString = EntityUtils.toString(entityresponse, "UTF-8");
response.close();
httpclient.close();
But I am getting this: java.net.SocketException: Connection reset
I've tried a lot of proxies and different URLs too but the same problem is there.
It work fine if I set a HTTP URL and the http parameter in the proxy host line, but I want HTTPS :/
Any help would be appreciated.
Thanks!
If you want to call https url, you must have to install the certificate in your jre security/lib folder.
In order to install the certificate, please follow below steps:
Download InstallCert.java file from : https://confluence.atlassian.com/download/attachments/180292346/InstallCert.java?version=1&modificationDate=1315453596921
copy InstallCert.java to any location.
run: javac InstallCert.java
run: java InstallCert example.com:port
jssecacerts file will be generated
Copy it inside JAVA_HOME\jre\lib\security folder
I hope this should resolve your issue.
I try to do a http request from my server and want to use different ip addresses (do one request with one IP and another with another IP). I read that it should work with the http client of apache. This is the code i use:
HttpClientBuilder builder = HttpClients.custom();
Builder configBuilder = RequestConfig.custom();
configBuilder.setLocalAddress(InetAddress.getByAddress(new byte[] {85,2,(byte) 246,4}));
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(configBuilder.build()).build();
HttpGet httpGet = new HttpGet("http://xy.com/");
CloseableHttpResponse response1 = httpClient.execute(httpGet);
//do something with the response
response1.close();
resulting in the following exception:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
at the line "CloseableHttpResponse response1 = httpClient.execute(httpGet);"
What am I doing wrong? (It don't has to be done with apache, it just needs to be java. Best would be Play Framework because I normally do my request with that but I just want it to work, anything else is secondary)
Thanks
I am suppose to send song (mp3/wav) file and some data through secure restful web service. I am using MultipartEntity to make HttpPost request. but When I execute it through HttpClient, the server replies this error
HTTP Status 400 - Bad Request
type: Status report
message : Bad Request
The request sent by the client was syntactically incorrect (Bad Request).
But the service is doing very well if we call it from its Web interface. please help
its the code
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost();
try {
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("email", new StringBody("test#testmail.com"));
reqEntity.addPart("password", new StringBody("123"));
reqEntity.addPart("title", new StringBody("My new song"));
reqEntity.addPart("musicData", new FileBody(new File(FilePath)));
// FIlePath is path to file and contains correct file location
postRequest.setEntity(reqEntity);
postRequest.setURI(new URI(ServiceURL));
HttpResponse response = httpclient.execute(postRequest);
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
I also included apache-mime4j, httpclient, httpcore and httpmime jars for MultipartEntity.
This is HTML page snap for the Service.
Try removing the setURI method and passing the URL in when you create your HttpPost object, as follows. This worked for me (more here).
HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(ServiceURL);
try {
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("email", new StringBody("test#testmail.com"));
reqEntity.addPart("password", new StringBody("123"));
reqEntity.addPart("title", new StringBody("My new song"));
reqEntity.addPart("musicData", new FileBody(new File(FilePath)));
postRequest.setEntity(reqEntity);
HttpResponse response = httpclient.execute(postRequest);
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
It seems header of the request is incorrect, this problem can occur if you use a different Auth protocol or upper/lower case or simply wrong things in header that server side can't handle.
Dont waste your time by trying different different combinations.There are some HTTP Request tools available for HTTP with which you can track request and response you are getting.Ex. HTTP Analyzer download trial version
Call URL from your working webinterface , copy request and response
then do same with from program the tool is enogh capable to capture your request and response data.
Now compare working and non working request you will surely able to dignose the issue whether it can be header issue or some authentication related issue.
I using HttpClient api to authenticate to a web site:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(args[0], args[1]));
HttpGet httpget = new HttpGet("http://..........");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
}
I have this answer:
HTTP/1.1 403 Forbidden
Response content length: -1
But with a browser i have access to this page with the same login and password !!!!
How can i fix this problem ?
You construct the AuthScope object with the port parameter set to 443 (default port for HTTPS). However, you create the HttpGet object with the URL pointing to HTTP (with default port 80).
Either try to construct the AuthScope using:
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT)
or make sure that ports will match.
You need to look carefully at how the browser is actually authenticating.
What you are trying to do is (I think) send the credentials using HTTP Basic Authentication. If the site is set up to only allow form-based authentication and a session cookie, then it will ignore the header containing the credentials.
Check if the Version of the HttpClient you are using is whats causing the 403.
Try
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();