I have created a simple java service in kony app.When i try to run the Test with input parameter i got the following exception.
java.lang.ClassCastException: com.kony.sample.KonyServerConnection cannot be cast to com.konylabs.middleware.common.JavaService
at com.konylabs.middleware.connectors.JavaConnector.execute(JavaConnector.java:142)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage.getJavaResponse(JavaServiceDefinitionEditorPage.java:1878)
at com.pat.tool.keditor.editors.JavaServiceDefinitionEditorPage$InvokeJavaOperation.run(JavaServiceDefinitionEditorPage.java:1842)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
i followed this Link for reference
i have shared some of java code
private static final String URL = "http://serverurl/sendEmail?";
public static String getServerPersponce(String entitiy,String mHeader){
String responseBody = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
System.out.println("Requesting : " + httppost.getURI());
try {
StringEntity entity = new StringEntity(entitiy);
if(mHeader != null && !mHeader.equalsIgnoreCase(""))
httppost.addHeader("AuthToken" , mHeader);
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity1 = response.getEntity();
InputStream stream = entity1.getContent();
responseBody = getStringFromInputStream(stream);
if (response.getStatusLine().getStatusCode() != 200) {
// responseBody will have the error response
}
//responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
return responseBody;
}
public static void main(String[] args) throws Exception {
String data = "{\"CC\":[\"yuvarajag#gmail.com\"],\"Content\":\"sample string 2\",\"Subject\": \"sample string 1\",\"To\": [\"yuvarajag#gmail.com\",\"sakumarr#gmail.com\",]}";
String result = getServerPersponce(data, accessToken);
System.out.println("Result "+result);
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString().trim();
}
This java code is working fine. after creating a jar i included this jar to the Kony app.I am getting exception in kony java service integration.
In the code specified there is no implementation of com.konylabs.middleware.common.JavaService2 class. JavaService will work if you implement JavaService2 class in your class file and override its invoke meathod.
below is the sample:
public class <YOUR CLASS NAME> implements JavaService2 {
#Override
public Object invoke(String serviceId, Object[] arg1,
DataControllerRequest arg2, DataControllerResponse arg3)
throws Exception {
// YOUR LOGIC
return result;
}
}
Kony JavaConnector expects classes that implements JavaServer or JavaService2. Apparently com.kony.sample.KonyServerConnection does not implements them.
Related
I want to pass JSON objects to web services like this
firstname=jhon&lastname=mic&mail=jhon#gmail.com&sex=M&hometown=blablabla
how can I pass,any one please help me.Am trying like this
JSONObject json = new JSONObject();
json.put("firstname", firstname);
json.put("lastname", laststname);
json.put("mail", mail);
json.put("sex", sex);
json.put("hometown", hometown)
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity!=null)
{
InputStream instream=entity.getContent();
String result=convertStreamToString(instream);
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
But this code not posted the right value to webservice,Is there any wrong please help me ,
Thank you:)
StringBuilder bu = new StringBuilder();
for(int i = 0; i<json.names().length(); i++){
bu.append("&");
try {
bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bu.toString();//give you parameters
I'm using DefaultHttpClient to make a GET request from a URL.
Please see code bellow.
That you can see, if log the result with Log.i("result", l), when the loop finished, I can see full data of the response,
but if I use htmlResult = sb.toString(); I cannot get or see all data, maybe only a half of the response.
What is wrong here? Thanks for your comments.
Edit: i posted my code that everyone can help me:
public class DetailParser {
HTTPAsyncRequest _asyncRequest;
CompletionHandler _completion;
private String _currentURL;
private static DetailParser _instance;
public GadgetItem _currentItem;
static InputStream _inputStream = null;
public static DetailParser getInstance()
{
if(_instance == null)
_instance = new DetailParser();
return _instance;
}
public class HTTPAsyncRequest extends AsyncTask<String, Integer, Response>
{
#Override
protected Response doInBackground(String... params) {
_currentURL = params[0];
String result = getData(params[0]);
Response response = new Response(result, params[0]);
return response;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Response response) {
if(response == null)
return;
if(!_currentURL.equals(response.urlRequest))
{
super.onPostExecute(response);
}
else
{
// TODO Auto-generated method stub
parseGadgetItem(response.xmlResult);
if(_completion != null)
_completion.getDescriptionDone(_currentItem);
super.onPostExecute(response);
}
}
public String getData(String url)
{
private String _resultHTML = null;
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
_inputStream = httpEntity.getContent();
reader = new BufferedReader(new InputStreamReader(_inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String l = "";
String nl = System.getProperty("line.separator");
while ((l = reader.readLine()) != null) {
sb.append(l + nl);
// Log.i("result", l);
// htmlResult += l + nl;
}
_resultHTML = sb.toString();
// Log.i("Result", _resultHTML);
// htmlResult = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
Log.e("GetMethodEx", e.getMessage());
}
}
return _resultHTML;
}
}
// constructor
public DetailParser() {
}
private void abortRequest()
{
if(_asyncRequest != null)
_asyncRequest.cancel(true);
}
public void getGadgetDescription(GadgetItem item, final CompletionHandler completion)
{
_currentItem = item;
_completion = completion;
abortRequest();
_asyncRequest = (HTTPAsyncRequest) new HTTPAsyncRequest().execute(item.gadget_link,null,null);
}
public void parseGadgetItem(String html) {
// HERE : data is missing
if (xml == null)
return;
try {
Document doc = Jsoup.parse(html);
Elements e = doc.getElementsByClass("thecontent entry-content");
//
} catch (Exception e) {
}
}
}
Try this:
Declare this globally
static InputStream re = null;
private String result = null;
Now use this code in your class
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response1;
try {
response1 = client.execute(httpGet);
Log.e("Refresh is: ", response1.toString());
HttpEntity entity = response1.getEntity();
re=entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(re, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String result= sb.toString();
System.out.println(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.
How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?
Should use it after execute
public static String httpPostToString(HttpPost httppost) {
StringBuilder sb = new StringBuilder();
sb.append("\nRequestLine:");
sb.append(httppost.getRequestLine().toString());
int i = 0;
for(Header header : httppost.getAllHeaders()){
if(i == 0){
sb.append("\nHeader:");
}
i++;
for(HeaderElement element : header.getElements()){
for(NameValuePair nvp :element.getParameters()){
sb.append(nvp.getName());
sb.append("=");
sb.append(nvp.getValue());
sb.append(";");
}
}
}
HttpEntity entity = httppost.getEntity();
String content = "";
if(entity != null){
try {
content = IOUtils.toString(entity.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
sb.append("\nContent:");
sb.append(content);
return sb.toString();
}
snippet
I usually do post in this way (The server answer is a JSON object) :
try {
postJSON.put("param1", param1);
postJSON.put("param2",param2);
} catch (JSONException e) {
e.printStackTrace();
}
String result = JSONGetHTTP.postData(url);
if (result != null) {
try {
JSONObject jObjec = new JSONObject(result);
}
} catch (JSONException e) {
Log.e(TAG, "Error setting data " + e.toString());
}
}
And postData is:
public static String postData(String url, JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = null;
try {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 30000);
HttpConnectionParams.setSoTimeout(myParams, 30000);
httpclient = new DefaultHttpClient(myParams);
} catch (Exception e) {
Log.e("POST_DATA", "error in httpConnection");
e.printStackTrace();
}
InputStream is = null;
try {
HttpPost httppost = new HttpPost(url.toString());
//Header here httppost.setHeader();
StringEntity se = new StringEntity(obj.toString());
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// // Do something with response...
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert response to string
BufferedReader reader = null;
String result = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
} finally {
try {
if (reader != null)
reader.close();
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (result != null) {
try {
#SuppressWarnings("unused")
JSONObject jObjec = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
return result;
}
Hope it helps
Well i actually did HTTP-Post using NameValuePair...... I am showing the code which i use to do an HTTP-Post and then converting the Response into a String
See the below Method code:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
I have created an applet which uses the HttpClient from Apache HTTP Components. The applet is supposed to open a remote webpage and print the source of the page to console. The code works fine when ran from IDE (NetBeans), however when deployed in a webpage it throws an AccessControlException:
access denied ("java.net.SocketPermission" "www.hardwarebase.net" "resolve")
Upon reading similar questions concerning the problem, it seemed like the problem was in the applet not being signed. I self-signed it, so when I ran it the next time, the applet asked for and got the permissions.
Still, I get the same exception. Here is the code of the main applet class:
public class MyApplet extends java.applet.Applet {
public DefaultHttpClient client;
public String useragent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1";
public void init()
{
resize(150,25);
client = new DefaultHttpClient();
String page = Get("http://www.hardwarebase.net"));
System.out.println(page);
}
public String Get(String url)
{
final HttpUriRequest request = new HttpGet(url);
request.setHeader("User-Agent", useragent);
HttpResponse response;
try {
response = (HttpResponse)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return client.execute(request);
} catch (IOException ex) {
Logger.getLogger(MyApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
);
return _getResponseBody(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String Post(String url, List<NameValuePair> nameValuePairs)
{
final HttpPost request = new HttpPost(url);
request.setHeader("User-Agent", useragent);
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
try {
response = (HttpResponse)AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
return client.execute(request);
} catch (IOException ex) {
Logger.getLogger(MyApplet.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
);
return _getResponseBody(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public void paint(Graphics g)
{
g.drawString("Hello world!", 50, 25);
}
public String _getResponseBody(final HttpEntity entity) throws IOException, ParseException
{
if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
InputStream instream = entity.getContent();
if (instream == null) { return ""; }
if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); }
String charset = getContentCharSet(entity);
if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; }
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try
{
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1)
{
buffer.append(tmp, 0, l);
}
}
finally
{
reader.close();
}
return buffer.toString();
}
public String getContentCharSet(final HttpEntity entity) throws ParseException
{
if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
String charset = null;
if (entity.getContentType() != null)
{
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0)
{
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) { charset = param.getValue(); }
}
}
return charset;
}
}
How can I resolve this AccessControlException?
I have resolved the issue by switching from HttpClient to URLConnection. I am not sure why doesn't URLConnection throw the exception, while HttpClient does.
I am not sure how to send HTTP Auth headers.
I have the following HttpClient to get requests, but not sure how I can send requests?
public class RestClient extends AsyncTask<String, Void, JSONObject> {
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/*
* This is a test function which will connects to a given rest service
* and prints it's response to Android Log with labels "Praeda".
*/
public JSONObject connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json) {
}
}
This is covered in the HttpClient documentation and in their sample code.
Maybe the documentation of HttpClient can help: link
Since Android compiles HttpClient 4.0.x instead of 3.x, below snippet is for your reference.
if (authState.getAuthScheme() == null) {
AuthScope authScope = new Au HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);thScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(preemptiveAuth, 0);