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();
}
Related
I have written the below code where I am sending XML content over a REST POST and then returning the response back to my calling function. I want my calling function to use the same connection for a defined time and should not create new connections again and again.
But this is not working as expected and its still creating new connections for every new request.
String out = null;
StringBuilder sb = new StringBuilder();
DefaultConnectionKeepAliveStrategy defaultConnectionKeepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response, context);
if (keepAlive == -1L)
keepAlive = 120000L;
return keepAlive;
}
};
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
HttpPost post = new HttpPost(url);
connectionManager.setMaxTotal(100);
connectionManager.setDefaultMaxPerRoute(100);
final int maxRetries = 3;
try (CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setRetryHandler((exception1, executionCount, context) -> {
try {
Thread.sleep(retryWaitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return (executionCount <= maxRetries);
}).setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
int waitPeriod = waitTime;
public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
this.waitPeriod *= 2;
return (executionCount <= maxRetries && response.getStatusLine().getStatusCode() >= 500);
}
public long getRetryInterval() {
return this.waitPeriod;
}
}).setKeepAliveStrategy(defaultConnectionKeepAliveStrategy).setConnectionTimeToLive(120L, TimeUnit.SECONDS).build()) {
try {
StringEntity requestEntity = new StringEntity(xml, ContentType.APPLICATION_XML);
post.setEntity(requestEntity);
CloseableHttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
} else {
.....
}
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
e.printStackTrace();
}
post.releaseConnection();
return out;
}
How can i improve the code?
I am trying to upload a audio file to my webserver. But don't know how to read the the response. Here is the very simplified test.php:
<?php
echo 'I want to see this in the Toast';
?>
fff And here is my onClick that must send the file to the webserver and get a response:
public void send(View v){
Uri uri = new Uri.Builder().scheme("http").authority("sub.domain.nl").path("test.php")
.appendQueryParameter("action", "sendMessage")
.appendQueryParameter("idto", "18")
.appendQueryParameter("idfrom", "36")
.appendQueryParameter("type", "audio")
.build();
String urlString = uri.toString();
new SendAudioTask().execute(urlString);
}
private class SendAudioTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"/audio.3gpp");
HttpResponse response = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
response = httpclient.execute(httppost);
} catch (Exception e) {
publishProgress(1);
}
return response.toString();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Toast.makeText(MainActivity.this, "Dev message: = " + values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
Result.toString() in the onPostExecute() is
org.apache.http.message.basicHttpRespons#43b4cc68
If toString() is the right way to read the response. What is wrong with my code? My code doesn't execute the publishProgress.
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);
private 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();
}
change
return response.toString();
to
return EntityUtils.toString(response.getEntity());
So what getEntity() does,
getEntity()
Obtains the message entity of this response, if any.
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 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.
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();
}