How to release PoolingHttpClientConnectionManager in httpclient4.5.4 - java

I got a problem while I am using httpclients 4.5.4.
When I close everything that is related to my connection, the PoolingHttpClientConnectionManager objects can not be Collected by java GC.
So as the application runs for about 1 month, I got an OOM exception.
My code is as same as example in https://hc.apache.org/httpcomponents-client-4.5.x/httpclient/examples/org/apache/http/examples/client/ClientConnectionRelease.java.
And InternalHttpClient objects can not be collected by java GC, either.
There is my code below, is there any objects holding the references of the two classes?
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
/**
* Http post请求
*/
public static String doHttpPost(String postUrl, Map<String, String> headers,
Map<String,String> params,String filePath) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost post = getHttpPost(postUrl, headers, params, filePath);
CloseableHttpResponse response = httpClient.execute(post);
try {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
inputStream = response.getEntity().getContent();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader.readLine();
}catch (Exception e) {
logger.warn("do http post fail : ", e);
}finally {
if (bufferedReader != null) {
logger.info("release bufferedReader: " + filePath);
bufferedReader.close();
}
if (inputStreamReader != null) {
logger.info("release inputStreamReader: " +filePath);
inputStreamReader.close();
}
if (inputStream != null) {
logger.info("release inputStream: " +filePath);
inputStream.close();
}
}
}
} catch (Exception e) {
logger.warn("do http post fail: ", e);
} finally {
if (response != null) {
logger.info("release response: " + filePath);
response.close();
}
if (post != null) {
logger.info("release HttpPost: " + filePath);
post.releaseConnection();
}
}
} catch (Exception e) {
logger.warn("do http post fail: ", e);
} finally {
if (httpClient != null) {
logger.info("release httpClient: " + filePath);
httpClient.close();
logger.info("release connectionManager: " + filePath);
httpClient.getConnectionManager().shutdown();
}
}
} catch (Exception e) {
logger.warn("do http post fail: ", e);
}
return "";
}
private static HttpPost getHttpPost(String postUrl, Map<String, String> headers,
Map<String, String> params, String filePath) {
HttpPost post = new HttpPost(postUrl);
String[] headerKeys = headers.keySet().toArray(new String[headers.keySet().size()]);
for (String key : headerKeys) {
post.setHeader(key, headers.get(key));
}
FileBody fileBody = new FileBody(new File(filePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addPart("express_image", fileBody);
String[] paramKeys = params.keySet().toArray(new String[params.keySet().size()]);
for (String key : paramKeys) {
StringBody valueBody = new StringBody(params.get(key), ContentType.TEXT_PLAIN);
multipartEntityBuilder.addPart(key, valueBody);
}
post.setEntity(multipartEntityBuilder.build());
return post;
}
}

I can't tell you why you run out of memory, but I can tell you, that it's no good idea to do it this way (despite you using a "recommended way").
I'm using CloseableHttpClient and PoolingHttpClientConnectionManager from version 4.5.3 and I never close them (they're both allocated once in a singleton and used for all requests). My application runs currently since maybe one month doing about one request per second (not really much).
Note that creating a new client for each connection is about as efficient as buying a new car for each trip.

Related

How can I upload pdf files in Egnyte using Rest API and Java

Having the PDF files in local drive(D:). Need to upload those PDF files in Egnyte with the help of Rest API and Java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
#SuppressWarnings("deprecation")
public class Postrequest {
public static void postRequest(String attachmentValue) throws Exception {
String attachment = "C:\\Users\\eclipse-workspace\\renamedfile\\"+attachmentValue;
String url = "https://domain.egnyte.com/pubapi/v1/fs-content/Shared/a/Sa/Upload/"+attachmentValue;
File inFile = new File(attachment);
FileInputStream fis = null;
FileBody data = new FileBody(inFile);
try {
fis = new FileInputStream(inFile);
HttpClient httpclient = HttpClientBuilder.create().build();
// server back-end URL
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Authorization", "Bearer " + "*****");
httppost.addHeader("Content-Disposition", "form-data; name=\"file\"");
//httppost.addHeader("Content-type", "****");
httppost.addHeader("Content-type", "text/plain");
httppost.addHeader("Host", "domain.egnyte.com");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("document", data);
HttpEntity httpEntity = entity.build();
httppost.setEntity(httpEntity);
// execute the request
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Assert.assertEquals(statusCode, 200,"The Status code is not matched");
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("[" + statusCode + "] " + responseString);
} catch (ClientProtocolException e) {
System.err.println("Unable to make connection");
} catch (IOException e) {
System.err.println("Unable to read file");
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
}
}
};

IOException: unexpected end of stream thrown HttpUrlConnection

I am getting an IOException: unexpected end of stream when trying to read the inputStream of an HttpUrlConnection. I have tested with other URL's like http://google.com and added urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0"); testing for an error on another helpful persons advice but no error occurred. My target SDK and buildSDK match. I am fetching results using the same class for other fragments with different URL's without problems. Since trying to change to another API I've come across this problem.
The URL I'm trying to fetch JSON results from - http://eventregistry.org/json/article?query=%7B%22%24query%22%3A%7B%22%24and%22%3A%5B%7B%22sourceUri%22%3A%7B%22%24and%22%3A%5B%22bbc.co.uk%22%5D%7D%7D%2C%7B%22lang%22%3A%22eng%22%7D%5D%7D%7D&action=getArticles&apikey=342f5f25-75ac-44b5-8da0441508e871e8&resultType=articles&articlesSortBy=date&articlesCount=10&articlesIncludeArticleImage=true
My code to fetch the JSON -
package com.example.android.greennewswire;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils(){
}
public static ArrayList<News> fetchNewsData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {String testString = readUrl(requestUrl); Log.i(LOG_TAG, "testString: " + testString);
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Error making HTTP request", e);
}
if (jsonResponse == null) {
return new ArrayList<News>();
}
ArrayList<News> news = extractBooks(jsonResponse);
return news;
}
public static URL createUrl(String stringUrl){
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Malformed URL", e);
} return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = null;
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
InputStream errorStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(10000);
urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0");
urlConnection.connect();
Log.e(LOG_TAG, "Response code: " + urlConnection.getResponseCode());
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromInputStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
String string = e.getCause().toString();
Log.e(LOG_TAG, "Problem reading from input stream, " + string, e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
} if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
Stack trace
Problem reading from input stream, java.io.EOFException: \n not found: size=14639 content=7b2261727469636c6573223a7b22726573756c7473223a5b7b226964223a2231...
java.io.IOException: unexpected end of stream on Connection{eventregistry.org:80, proxy=DIRECT# hostAddress=185.49.3.27 cipherSuite=none protocol=http/1.1} (recycle count=0)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:905)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:789)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:501)

Android application - post data to a Google form

I have a problem with my android application. I am trying to make the users fill out a form in the application and send their responses to a Google form online, which would record the responses in a Google spreadsheet. Everything seems fine in the application itself and I encounter no errors there, but only the timestamp shows in the response spreadsheet and no text.
This is my code for the postData method:
public void postData(){
String url = getString(R.string.post_URL);
String name = "testname";
Log.i("test",name);
String lunch = "testlunch";
Log.i("test", lunch);
String vegetarian="testveg";
Log.i("test",vegetarian);
String allergies = "testaler";
Log.i("test",allergies);
String special = "testspec";
Log.i("test",special);
HttpRequest request = new HttpRequest();
try {
String data = R.string.entry_name + URLEncoder.encode(name, "UTF-8") + "&" +
R.string.entry_lunch + URLEncoder.encode(lunch, "UTF-8") + "&" +
R.string.entry_vegetarian + URLEncoder.encode(vegetarian, "UTF-8") + "&" +
R.string.entry_allergies + URLEncoder.encode(allergies, "UTF-8") + "&" +
R.string.entry_special + URLEncoder.encode(special,"UTF-8");
String response = request.sendPost(url,data);
Log.i("response",response);
}
catch(UnsupportedEncodingException e){
Log.d("Unsupported exception", e.toString());
}}
I'm using this URL of the google form:
https://docs.google.com/forms/d/1XPaQe0j86XwcxbO13uxZRawCwUexyJMHdPlPLoQaD1A/formResponse
For the entries, I am using strings formatted like this:
entry.569049980
This is how I call the function (only temporarily):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Connection().execute();
}
private class Connection extends AsyncTask {
#Override
protected Object doInBackground(Object...arg0){
postData();
return null;
}
The HttpRequest file, which I am using comes from here
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/*
* This helper class was created by StackOverflow user: MattC https://stackoverflow.com/users/21126/mattc
* IT was posted as an Answer to this question: https://stackoverflow.com/questions/2253061/secure-http-post-in-android
*/
public class HttpRequest {
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public HttpRequest(){
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data) {
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data) {
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType) {
ret = null;
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY,
CookiePolicy.NETSCAPE );
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : " + e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try {
response = httpClient.execute(httpPost,localContext);
if (response != null) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}
Do I need to use the Drive API or can I make some modifications to make this work? (This seems to be much easier and I am not experienced at all with the Drive API)
You entries format should be "entry_number" and some corrections in your data. Hope this will help you.
String data = "entry_number1lkjhgfdrtyuo=" + URLEncoder.encode(col1) + "&" +
"entry_number2=" + URLEncoder.encode(col2) + "&" +
"entry_number3=" + URLEncoder.encode(col3);

HTTPclient POST with problematic web site

I'm trying to retrive some data from a web site.
I wrote a java class which seems to work pretty fine with many sites but it doesn't work with this particular site, which use extensive javascript in the input fomr.
As you can see from the code I specified the input fields taking the name from the HTML source, but maybe this website doesn't accept POST request of this kind?
How can I simulate an user-interaction to retrieve the generated HTML?
package com.transport.urlRetriver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class UrlRetriver {
String stationPoller (String url, ArrayList<NameValuePair> params) {
HttpPost postRequest;
HttpResponse response;
HttpEntity entity;
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(url);
postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params));
response = httpClient.execute(postRequest);
entity = response.getEntity();
if(entity != null){
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (Exception e) {
result = "We had a problem";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
void ATMtravelPoller () {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
String url = "http://www.atm-mi.it/it/Pagine/default.aspx";
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_s", "Viale romagna 1"));
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_e", "Viale Toscana 20"));
params.add(new BasicNameValuePair("sf_method", "POST"));
String result = stationPoller(url, params);
saveToFile(result, "/home/rachele/Documents/atm/out4.html");
}
static void saveToFile(String toFile, String pos){
try{
// Create file
FileWriter fstream = new FileWriter(pos);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
At my point of view, there could be javascript generated field with dynamic value for preventing automated code to crawl the site. Send concrete site you want to download.

The type Enum is not generic; it cannot be parameterized with arguments <RestClient.RequestMethod>

The type Enum is not generic; it cannot be parameterized with arguments <RestClient.RequestMethod>
I've this error in the following code ..
package ayanoo.utility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.util.Log;
public class RestClient {
public enum RequestMethod
{
GET,
POST
}
private Vector <NameValuePair> params;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new Vector<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws IOException
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "/";
for(NameValuePair p : params)
{
//String paramString = p.getName() + "=" + p.getValue();
String paramString = p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
Log.d("URL See:",url + combinedParams);
URL urlObject = new URL(url + combinedParams);
//URL urlObject = new URL("http://www.aydeena.com/Services/Search.svc/JSON/SearchByText/1");
executeRequest(urlObject);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(URL urlObject) throws IOException{
HttpURLConnection con = null;
con = (HttpURLConnection) urlObject.openConnection();
con.setReadTimeout(10000 /* milliseconds */);
con.setConnectTimeout(15000 /* milliseconds */);
con.setRequestMethod("GET");
//con.addRequestProperty("Referer",
// "http://www.pragprog.com/titles/eband/hello-android");
con.setDoInput(true);
// Start the query
con.connect();
response = convertStreamToString(con.getInputStream());
Log.d("Response:", response);
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
Log.d("Test URL:", url);
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
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();
}
}
what's the problem ??? !
I had the same problem, and it turned out that it was because the standard lib was not in the eclipse class path for the project. Just go into Build Path -> Add Libraries and add the JRE System Library
Are you sure the Java compiler is set to 1.5 (default for android) or better? If you are using Eclipse you can see that from the preferences.
I had the same problem.
I only had one error in my project which was the "is not generic one'.
After I commented out the Enum code I found a lot more errors.
There seemed to be some kind of hold-up. Only after fixing the other errors and then removing the comments did it work.
Yes I also saw this error message for a project that was previously working fine.
I checked the compiler version (I am using 1.6) as well as the system library (it is already being used) to no avail.
Finally I just closed the project and then re-opened it, and then the problem went away. Sounds like an Eclipse bug to me.

Categories

Resources