HTTPURLConnection - empty response - java

This is probably a common question but I can't figure it out.
I have this URL which returns the expected ticket detail if I plug it into a browser, so I know it is working:
https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails?actionString=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-16%22%3F%3E%0A%3CGetTicketAction%20xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchemainstance%22%20xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%0A%3CCompanyName%3Exxxxxxx%3C%2FCompanyName%3E%3CIntegrationLoginId%3Exxxxxx%3C%2FIntegrationLoginId%3E%3CIntegrationPassword%3Exxxxxx%3C%2FIntegrationPassword%3E%0A%3CSrServiceRecid%3E1921%3C%2FSrServiceRecid%3E%3C%2FGetTicketAction%3E
For a more readable version it is this URL:
https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails
Followed by:
?actionString=
Followed by this xml:
<?xml version="1.0" encoding="utf-16"?>
<GetTicketAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>xxxx</CompanyName><IntegrationLoginId>xxxx</IntegrationLoginId><IntegrationPassword>xxxx</IntegrationPassword>
<SrServiceRecid>1921</SrServiceRecid></GetTicketAction>
I am having problems putting this into code and getting it to work.
I get this error:
???????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????? o?????????????????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????o???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
com.google.gwt.xml.client.impl.DOMParseException: Failed to parse: error on line 1 at column 1: Document is empty
at com.google.gwt.xml.client.impl.XMLParserImplSafari.throwDOMParseException(XMLParserImplSafari.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.xml.client.impl.XMLParserImplSafari.parseImpl(XMLParserImplSafari.java)
at com.google.gwt.xml.client.impl.XMLParserImpl.parse(XMLParserImpl.java:278)
at com.google.gwt.xml.client.XMLParser.parse(XMLParser.java:47)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest.processXML(HelpDeskTest.java:232)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest$2$1.onSuccess(HelpDeskTest.java:199)
at com.google.gwt.HelpDeskTest.client.HelpDeskTest$2$1.onSuccess(HelpDeskTest.java:1)
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:232)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor29.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:695)
On this line:
System.out.println(line);
Here is all the code. As you can see I've tried setting serverParameters to both a URL encoded string as well as an xml string:
package com.google.gwt.HelpDeskTest.server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.google.gwt.HelpDeskTest.shared.HelpDeskTestException;
#SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
HelpDeskTestService {
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
final String serverPath = "https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails";
System.out.println(serverPath);
//DO I need to URL encode this???
//I’ve tried this:
//final String serverParameters= "%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-16%22%3F%3E%0A%3CGetTicketAction%20xmlns%3Axsi%3D%22http%3A%2F%2F" +
//"www.w3.org%2F2001%2FXMLSchema-instance%22%20xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%0A%3CCompanyName" +
//"%3Exxxxx%3C%2FCompanyName%3E%3CIntegrationLoginId%3Exxxxx%3C%2FIntegrationLoginId%3E%3CIntegrationPassword%3Exxxxx%3C%2F" +
//"IntegrationPassword%3E%0A%3CSrServiceRecid%3E1921%3C%2FSrServiceRecid%3E%3C%2FGetTicketAction%3E";
final String serverParameters="<?xml version=%221.0%22 encoding=%22utf-16%22?><GetTicketAction xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22 xmlns:xsd=%22http://www.w3.org/2001/XMLSchema%22><CompanyName>xxxx</CompanyName><IntegrationLoginId>xxxx</IntegrationLoginId><IntegrationPassword>xxxx</IntegrationPassword><SrServiceRecid>1921</SrServiceRecid></GetTicketAction>";
System.out.println(serverParameters);
//Open HttpURLConnection:
URL url = new URL(serverPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-16");
connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(serverParameters);
wr.flush();
wr.close();
//process response - need to get xml response back.
InputStream stream = connection.getInputStream();
//put output stream into a string
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"utf-16"));
String result = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
result+= line;
}
br.close();
connection.disconnect();
System.out.println(result);
return result;
} catch (final Exception e) {
System.out.println(e.getMessage());
throw new HelpDeskTestException();
//handle timeout error
}
}
}

I have got 'Server returned HTTP response code: 500 for URL: myconnectwise.net/v4_6_release/services/system_io/…; after executing of your code.
So check server (500 - Internal Server Error).
And analyze response code before parsing result as XML.

Related

REST api request

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.population.population.estimator.model.Country;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class PopulationService {
public void getPopulation() {
String query_url = "https://data.opendatasoft.com/api/records/1.0/search/?dataset=world-population%40kapsarc&facet=country_name&facet=year&refine.country_name=Australia&refine.year=2000";
try {
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(25000);
conn.setRequestProperty("content-type","application/json; charset=utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.connect();
OutputStream out = conn.getOutputStream();
int status = conn.getResponseCode();
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
getPopulation();
}
}
Following is the output showing exception details.
java.io.IOException: Server returned HTTP response code: 400 for URL:
https://data.opendatasoft.com/api/records/1.0/search/?dataset=world-population%40kapsarc&facet=country_name&facet=year&refine.country_name=Australia&refine.year=2000
Stack Trace:
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1890)
at sun.net.www.protocol.http.HttpURLConnection$10.run(HttpURLConnection.java:1885)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1884)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1457)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at org.population.population.estimator.service.PopulationService.getPopulation(PopulationService.java:55)
at org.population.population.estimator.resources.PopulationResource.getPopulation(PopulationResource.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:143)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:160)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:203)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:97)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:303)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:286)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1072)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:399)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1579)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Server returned HTTP response code: 400 for URL: https://data.opendatasoft.com/api/records/1.0/search/?dataset=world-population%40kapsarc&facet=country_name&facet=year&refine.country_name=Australia&refine.year=2000
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at org.population.population.estimator.service.PopulationService.getPopulation(PopulationService.java:52)
... 48 more
just placing the query in the browser returns a response but through my program, I get an error. If someone can hellp I would be grateful.
Im creating a rest service
First you have to use InputStream since you are reading data from the response. Second, you have to accept as json response for that you have to use conn.setRequestProperty("Accept", "application/json");
I have modified your program, please check.
public class PopulationService {
public static void getPopulation() {
String query_url =
"https://data.opendatasoft.com/api/records/1.0/search/?dataset=world-population#kapsarc&facet=country_name&facet=year&refine.country_name=Australia&refine.year=2000";
try {
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Response Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
int status = conn.getResponseCode();
System.out.println("Status Code: "+status);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
getPopulation();
}
}

Java HttpsURLConnection instance not giving response code

I am trying to get a token for an API with this code and it throws exception when it tries to get and check the response code. It is my understanding that url.openConnection() does not actually connect? I tried url.connect() but that didn't work for me. When I
System.out.println(conn);
i just get this:
sun.net.www.protocol.https.DelegateHttpsURLConnection:https://fim.api.ENV.fleetmatics.com/token
and when I
System.out.println(conn.getResponseCode());
I do not get anything.
public TokenGenerator(String username, String password, String getTokenUri){
_username = username;
_password = password;
_getTokenUri = getTokenUri;
_authString = GetToken();
}
private String GetToken(){
String authString = "";
try
{
// Get authentication, Base64 encoded, string
String basicAuth = BuildBasicAuth(_username, _password);
URL url = new URL(_getTokenUri);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "text/plain");
conn.setDoOutput(false);
// Execute request;, read response. If we do not receive a 200 OK, throw exception
if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
When I try to connect with this code, I get the stack trace below..
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.connect();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "text/plain");
conn.setDoOutput(false);
java.net.UnknownHostException: fim.api.ENV.fleetmatics.com
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at TokenGenerator.GetToken(TokenGenerator.java:52)
at TokenGenerator.<init>(TokenGenerator.java:39)
at Program.main(Program.java:10)
Exception in thread "main" java.lang.NullPointerException
at java.util.Date.getMillisOf(Unknown Source)
at java.util.Date.after(Unknown Source)
at TokenGenerator.GetAuthString(TokenGenerator.java:28)
at Program.main(Program.java:13)

PayPalRESTException: Connection timed out: connect

I have tried many ways but i am always getting the same exception, PayPalRESTException: Connection timed out: connect . I have even downloaded sample code provided by paypal and tried using those code, but still same error.
Please help me to come out from this problem. or at least provide your opinion.
Error Log :
SEVERE: Servlet.service() for servlet [signup] in context with path [/PayPalDemo] threw exception [com.paypal.core.rest.PayPalRESTException: Connection timed out: connect] with root cause
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.paypal.core.HttpConnection.execute(HttpConnection.java:93)
at com.paypal.core.rest.OAuthTokenCredential.generateOAuthToken(OAuthTokenCredential.java:132)
at com.paypal.core.rest.OAuthTokenCredential.generateAccessToken(OAuthTokenCredential.java:95)
at com.paypal.core.rest.OAuthTokenCredential.getAccessToken(OAuthTokenCredential.java:86)
at com.paypal.util.AccessTokenGenerator.getAccessToken(AccessTokenGenerator.java:20)
at com.paypal.util.AppHelper.createCreditCard(AppHelper.java:54)
at com.paypal.controller.UserServlet.handleSignup(UserServlet.java:268)
at com.paypal.controller.UserServlet.doPost(UserServlet.java:117)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I have visited several blogs also for figure out this problem but they suggested to check request URL.
I am using sendbox environment so i have provided following url :
https://api.sandbox.paypal.com
This is my SDK configuration file :
# Connection Information
http.ConnectionTimeOut=5000
http.Retry=1
http.ReadTimeOut=30000
http.MaxConnection=100
# HTTP Proxy configuration
# If you are using proxy set http.UseProxy to true and replace the following values with your proxy parameters
http.UseProxy=false
#http.ProxyPort=8080
#http.ProxyHost=127.0.0.1
#http.ProxyUserName=null
#http.ProxyPassword=null
#Set this property to true if you are using the PayPal SDK within a Google App Engine java app
http.GoogleAppEngine = false
# Service Configuration
service.EndPoint=https://api.sandbox.paypal.com
clientID=EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp (changed my own)
clientSecret=EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp (changed my own)
Servlet File :
package com.paypal.api.payments.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.paypal.api.payments.Address;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.Authorization;
import com.paypal.api.payments.CreditCard;
import com.paypal.api.payments.Details;
import com.paypal.api.payments.FundingInstrument;
import com.paypal.api.payments.Payer;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.Transaction;
import com.paypal.api.payments.util.GenerateAccessToken;
import com.paypal.core.rest.APIContext;
import com.paypal.core.rest.PayPalRESTException;
import com.paypal.core.rest.PayPalResource;
public class GetAuthorizationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger
.getLogger(GetAuthorizationServlet.class);
public void init(ServletConfig servletConfig) throws ServletException {
InputStream is = GetAuthorizationServlet.class
.getResourceAsStream("/sdk_config.properties");
try {
System.out.println("in read::");
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
e.printStackTrace();
LOGGER.fatal(e.getMessage());
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
APIContext apiContext = null;
String accessToken = null;
try {
accessToken = GenerateAccessToken.getAccessToken();
System.out.println("Access Token ::"+accessToken);
} catch (PayPalRESTException e) {
e.printStackTrace();
req.setAttribute("error", e.getMessage());
}
req.getRequestDispatcher("response.jsp").forward(req, resp);
}
}
Utility file that will get token from paypal
package com.paypal.util;
import com.paypal.core.ConfigManager;
import com.paypal.core.rest.OAuthTokenCredential;
import com.paypal.core.rest.PayPalRESTException;
public class AccessTokenGenerator {
private static String accessToken;
public static String getAccessToken() throws PayPalRESTException {
if (accessToken == null) {
// ClientID and ClientSecret retrieved from configuration
String clientID = ConfigManager.getInstance().getValue("clientID");
String clientSecret = ConfigManager.getInstance().getValue("clientSecret");
accessToken = new OAuthTokenCredential(clientID, clientSecret).getAccessToken();
}
return accessToken;
}
}
Thanks in advanced.
I was facing this problem continuously since last 9 hrs but now i found the solution.
There is no error in code implementation but my firewall was not let them go to connect.
When i was turned off my firewall from control panel then all code works perfectly.
Thanks you

URLConnection class java.net.ConnectException: Connection refused: connect

I am programming on a system with client running Java Applet on one end and server on the other. Now I have the client and server on the same computer. But as a client, I cannot see the applet and I get error like below:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at MainJApplet.init(MainJApplet.java:58)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at RequestServer.sendRequest(RequestServer.java:25)
at createGUI.createEditingBar(createGUI.java:1313)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
java.lang.NullPointerException
at createGUI.createEditingBar(createGUI.java:1315)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
Below is where the problem traced back:
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); // exception happens
I checked http://localhost:8080/ and port conflict. I have turn off windows firewall and yet the problem exists. Can someone kindly point me some direction? Any advice would be great! Thanks ahead!
I apologize for the long code. The first is for client.
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class MainJApplet extends JApplet {
GUI gui = new GUI();
Thread renewThread;
public void init() {
//pass parameters from url to applet
String filePath = this.getParameter("FilePath");
//temporary solution to bypass the new extention
String userName = this.getParameter("UserName");
String ipAddr = this.getParameter("IpAddress");
String userLevel = this.getParameter("UserLevel");
String ticket = this.getParameter("Ticket");
String accessMode = this.getParameter("AccessMode"); //1-normal 2-shared 3-email
//sharedTo will be get from the file path infor
String sharedTo = this.getParameter("ShareTo");
String type = this.getParameter("Type");
gui.shareTo = sharedTo;
gui.ticket = ticket; //this gui.ticket is used to varify email access, will be replaced
String relativePath = "";
try {
//connect to servlet
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
//Passing NAME+FILE+TICKET+TYPE to server at the initialization stage
out.write("IN");
out.write(userName + "#");
out.write(filePath + "#");
out.write(ticket + "#");
out.write(type + "#");
out.close();
//Wait for server response
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String dcodedStr;
StringBuffer decodedStringBuffer = new StringBuffer("");
while ((dcodedStr = in.readLine()) != null) {
decodedStringBuffer.append(dcodedStr);
}
String dStr = decodedStringBuffer.toString();
in.close();
if (dStr.equals("NOT_AUTHORIZED")) { //not passing authentication check
JOptionPane.showMessageDialog(new JFrame(),
"Access Denied",
"Warning!",
JOptionPane.ERROR_MESSAGE);
return;
} else {//pass authentication check
String[] initResp = dStr.split("#");
gui.FID = initResp[0]; //file ID
gui.EditMode = Boolean.parseBoolean(initResp[1]);
gui.userLevel = 1; //temporary set all as normal user
boolean firstOpen = Boolean.parseBoolean(initResp[2]);
relativePath = initResp[3];
if (initResp[4].trim().equals("normal")) {//owner
gui.accessMode = 1;
} else {//shared user
gui.accessMode = 2;
}
}
}catch(UnknownServiceException exp){
exp.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
gui.check_upon_window_close();
if (gui.is_new_drawing == 0) {
//2010.9.29 workDir -> FID
if (gui.EditMode) {
RequestServer.canClose(gui.IpAddress, gui.user, gui.FID);
} else {
RequestServer.canCloseNoEdit(gui.IpAddress, gui.user, gui.FID);
}
}
renewThread.stop();
}
}
Based off your comments my guess is that your server is binding to the loopback address (127.0.0.1, aka localhost). You didn't post what the server software is, but change it's configuration so that it binds on 0.0.0.0 instead. That should fix your issue.

How to write on web server in java

HI I am having problem in java related to write on the web server from the client. I am using following code please help me where I am wrong
For Server class
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class Server
{
public static void main(String args[]){
try{
ServerSocket s = new ServerSocket(8080);
System.out.println("ashish");
Socket incoming = s.accept();
System.out.println("the status of the socket="+incoming.isConnected());
InputStream inStream = incoming.getInputStream();
InputStreamReader isr=new InputStreamReader(inStream);
BufferedReader br=new BufferedReader(isr);
String str=null;
while((str=br.readLine()).equals("exit")==false){
System.out.println(str);
}
System.out.println("System exit");
}catch(Exception e){
e.printStackTrace();
}
}
}
And for the client class which is actually applet have folowing code
import java.applet.Applet;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class testApplet extends Applet
{
public void init(){}
public void start(){
try{
URL url = new URL("http://localhost:8080");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
PrintWriter out = new PrintWriter( httpCon.getOutputStream());
out.print("Resource content\n");
out.print("exit");
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void stop(){}
public void destroy(){}
}
Now when I run the server then the server display only the following
PUT / HTTP/1.1
User-Agent: Mozilla/4.0 (Windows Vista 6.1) Java/1.6.0
Host: localhost:8080
Accept: text/html, image/gif. image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
But it did not write the content which I write by the out object of PrintWriter
and next goes into wait state
on the other hand the applet does not started just initiated. and when I close server program then applet gives following exception
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at testApplet.start(testApplet.java:19)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please tell what's wrong with me
Try
httpCon.setChunkedStreamingMode(0);
before writing to outputstream. You should always do this on http connections if content length is not known in advance.

Categories