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);
Related
I created a class for my android application that connects to mysql database using json.. note that the php code getNews.php is tested and it responds with the required data in json format properly. And note that i only want to get an array containing the data with this class ArrayReceiver.java ... it isn't working though... can anyone check the code please.
ArrayReceiver.java
package com.example.batoul.uptodate4;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArrayReceiver extends AsyncTask<String, Integer, String> {
List<Article> a=new ArrayList<Article>();
String url="192.168.11.8/utd/getNews.php";
Boolean error = false;
private ProgressDialog pDialog;
Boolean success = false;
String msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public List<Article> getA() {
return a;
}
#Override
protected String doInBackground(String... arg) {
publishProgress(2);
// agendaArrayList = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>();
try {
// params.add(new BasicNameValuePair("notActivated", "false"));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url,
ServiceHandler.POST, params);
// Log.e("aaa ", "> " + ServiceHandler.url);
// Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
//int catObj22 = jsonObj.getInt("success");
// if (catObj22 == 1) {
JSONArray titles = jsonObj.getJSONArray("title");
for (int i = 0; i < titles.length(); i++) {
String catObj = (String) titles.get(i);
Article obj = new Article(0,"");
obj.setTitle(catObj);
a.add(obj);
}
success = true;
} else {
success = false;
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
} catch (Exception e) {
error = true;
return null;
}
Log.e("aaa ", " success");
return "success";
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if (pDialog.isShowing()) {
// pDialog.dismiss();
// }
// Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
if (success) {
// for (int i = 0; i < travelsArr.size(); i++) {
// new getPic().execute("" + i);
// }
//ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
//SubjectListView.setAdapter(adapter);
}
}
}
ServiceHandler.java
package com.example.batoul.uptodate4;
import android.util.Log;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public static String url ,u;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
this.url =url +"?" + paramString;
}
HttpGet httpGet = new HttpGet(this.url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader 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");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
getNews.php :
<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
$query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
array_push($title, $row["title"]);// need change
}
$response["success"] = 1;
$response["title"] = $title;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>
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.
I want to get response from url but it returns caught exception.
In detail, I created activity which will get two input variable emailid and password.
There is one login button, clicking on the login button will invoke the getquizzes function.
Here is the code that I am using:
public void getquizzes(View view) {
emailid = (EditText) findViewById(R.id.email);
ipassword = (EditText) findViewById(R.id.password);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP | Gravity.LEFT, 10, 10);
// Toast toast = Toast.makeText(context, text, duration);
// toast.makeText(LoginActivity.this, emailid.getText(), toast.LENGTH_SHORT).show();
String rurl = "http://www.savsoftquiz.com/quizdemo/index.php/verifylogin/api_login/" + emailid.getText() + "/" + ipassword.getText();
Toast.makeText(this, verifylogin(rurl), Toast.LENGTH_LONG).show();
}
private String verifylogin(String rurl){
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(rurl);
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
return line;
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
} catch (Exception e) {
return "Caught Exception";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
Use this format. Also store your edit text value in string variable.
class Login extends AsyncTask<String, String, String> {
String email ;
String pass ;
JSONObject json=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
parametres.add(new BasicNameValuePair("email", email));
parametres.add(new BasicNameValuePair("password", pass));
JSONObject json = jsonParser.makeHttpRequest(url,
"GET", parametres);
try {
// Checking for SUCCESS TAG
int success = json.getInt(KEY_SUCCESS);
if (success == 1) {
//yourcode
}
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println(is + "post");
}else if(method == "GET"){
System.out.println("1");
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
System.out.println("2");
String paramString = URLEncodedUtils.format(params, "utf-8");
System.out.println("3");
url += "?" + paramString;
System.out.println("4");
HttpGet httpGet = new HttpGet(url);
System.out.println("5");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("6");
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("7");
is = httpEntity.getContent();
System.out.println(is + "get");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("TagCovertS", "["+json+"]");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
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.
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.