IOException: unexpected end of stream thrown HttpUrlConnection - java

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)

Related

How to release PoolingHttpClientConnectionManager in httpclient4.5.4

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.

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);

Android Http Get Request

I'm a newbie at android development. I'm trying to send a GET request to an URL. I wrote the below code.
public void searchProducts(View v)
{
//String txtSearchTerm = ((EditText)findViewById(R.id.txtsearch)).getText().toString();
//String termCleaned = txtSearchTerm.replace(' ', '+').toString();
AlertDialog alertMessage = new AlertDialog.Builder(this).create();
alertMessage.setTitle("Loading");
alertMessage.setMessage(GET("http://webkarinca.com/sample.json"));
alertMessage.show();
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
{
result = convertInputStreamToString(inputStream);
}
else
{
result = "Did not work!";
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I already put imports head of the class. There they are
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
It doesn't work and at the Problems section it shows as a warning
The type HttpGet is deprecated
The type HttpResponse is deprecated
Try this. it worked for me.
first must implement this on build.gradle: app
implementation("com.squareup.okhttp3:okhttp:4.8.0")
then, use this method
String run(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
Finally, call it on onCreate method
run("enter your URL here");
try this
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import android.content.Context;
import com.jivebird.settings.CommonMethods;
public class Connecttoget {
public static String callJson(Context context,String urlstring){
String data=null;
try {
URL url = new URL(urlstring);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
data = convertStreamToString(stream);
stream.close();
}catch(SocketTimeoutException e){
CommonMethods.createAlert(context, "Sorry, network error", "");
}
catch (Exception e) {
e.printStackTrace();
}
return data;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
Can you try the below code,if it helps.
HttpURLConnection urlConnection = null;
URL url = null;
JSONObject object = null;
InputStream inStream = null;
try {
url = new URL(urlString.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
inStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
String temp, response = "";
while ((temp = bReader.readLine()) != null) {
response += temp;
}
object = (JSONObject) new JSONTokener(response).nextValue();
} catch (Exception e) {
this.mException = e;
} finally {
if (inStream != null) {
try {
// this will close the bReader as well
inStream.close();
} catch (IOException ignored) {
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Try this code. This worked for me.
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class ServerTest extends Activity {
private String TAG = "test";
private String url = "http://webkarinca.com/sample.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Download().execute();
}
public class Download extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String out = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
out = EntityUtils.toString(httpEntity, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e(TAG, result);
}
}
}
Also make sure you have added this to manifest,
<uses-permission android:name="android.permission.INTERNET" />
and also make sure you are connected to the internet.

C drive memory overloading by running swing

I'm making a management software in java for a book store. There is a database on my server. I get my database data by php code.which is also in my server.I use the code below to get data by running the php code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpUtility {
private static HttpURLConnection httpConn;
public static HttpURLConnection sendGetRequest(String requestURL)
throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true);
httpConn.setDoOutput(false);
return httpConn;
}
public static HttpURLConnection sendPostRequest(String requestURL,
Map<String, String> params) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true);
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
httpConn.setDoOutput(true);
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
OutputStreamWriter writer = new OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
return httpConn;
}
public static String readSingleLineRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String response = reader.readLine();
reader.close();
return response;
}
public static String[] readMultipleLinesRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
List<String> response = new ArrayList<String>();
String line = "";
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
return (String[]) response.toArray(new String[0]);
}
public static void disconnect() {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
Now I'm facing a problem like the image link (don't have enough reputation for the upload)below.There are 3 image link.
before log in
After the log in and before the search query
Another link is in the comment.
After every request making my C:// drive is loosing 10 MB space and I don't know why(Very noob coder sorry.)
Can anyone help me.

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