I have a task to ping and endpoint using a post request. The issue I am having is the full endpoint is not clearly defined. I have a docker image and container but I am not sure how to use it in order to make a successful api call.
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("/auth");
//Auth object just has 1 field called account
Auth a = new Auth("Test-acc");
Gson gson= new Gson();
String json = gson.toJson(a);
System.out.println("Json: " + json);
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Api-Key", "API Key is given for Test-acc");
CloseableHttpResponse response = client.execute(httpPost); //error as unknown endpoint?
client.close();
//read response
HttpEntity res = response.getEntity();
String result = EntityUtils.toString(res);
The error I get is: client.ClientProtocolException. The endpoint /auth gives me back a session token but I am unsure how to call the full endpoint (e.g. https://.../auth). I assume it has something to do with the docker container that is provided.
To test that the container is running I run docker run and get the response {"message": "ok"}. But other than that, I am unsure how to use it. Will the image in the container help with this?
Docker run command:
docker run -p 7902:7902 tesingCompany/testprovider
You have two choices :
You lanch this code from another container on the same user defined docker network, in this case the host is the container name
You launch this code from your host and you need to link a port from your host to a port on your container. You do that when you launch your container with the -p 7092:7092 option. It means your host 7092 port is linked to your container 7092, and you can contact it with localhost:7092
Related
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 have googled but many concerns was "java.lang.IllegalStateException: Target host must not be null", but in my case error was "java.lang.IllegalStateException: Target host is null"
I am trying to post a request using following code
StringEntity reqContent = new StringEntity(xmlData);
reqContent.setContentType("text/xml");
HttpPost req = new HttpPost(serverURL);
req.setEntity(reqContent);
httpClient = new DefaultHttpClient(connMgr, params);
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
HttpResponse response = httpClient.execute(req);
After executing the request I am getting "Target host is null".
I am giving a valid host. Does this error comes when Target host which I am trying to access is not available?
When sending a request , somehow my URL which I want to send the request to is getting null which caused this issue when I am trying to execute a request.
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'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".
I am developing one application which is connecting to server to get some data.
In this I want to check first if application is connected to server or not. And then, if server is on or off? Based on the result I want to do my further manipulations.
So how do I get the result of server status?
Here is the code which I am using:
Code:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://192.168.1.23/sip_chat_api/getcountry.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
}
Maintaining session cookies is best choice here, please see how to use session cookie: How do I make an http request using cookies on Android?
here, before sending request to server, check for session cookie. If it exists, proceed for the communication.
Update:
The Java equivalent -- which I believe works on Android -- should be:
InetAddress.getByName(host).isReachable(timeOut)
Check getStatusLine() method of HttpResponse
any status code other than 200 means there is a problem , and each status codes points to different problems happened.
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/StatusLine.html#getStatusCode()