I have a simple form and i need to send it to a URL with the parameters.
Let's say I have one parameter called token and I want to send it to example.com/?token=the_token
I don't need to handle or get the output, just send it to this url.
How I can do this? I've been trying for hours to use URLCONNECTION and HTTPURLCONNECTION and nothing worked.
Since I tried many things and nothing worked, I am trying from scratch.
This is it:
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the token to example.com/?token=token. The URL will add the token to my database with PHP.
}
Please do not reply with DefaultHttpClient. It is deprecated.
Trying URLConnection():
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the tokeb to example.com/?token=token
URLConnection connection = null;
try {
connection = new URL("mysite.com/send.php?id=my_id").openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");
try {
InputStream response = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
Look, I built a whole web/http communications class last year. I'm copying you the chunk which deals with get(s):
Import at least the following:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
try{
String mainUrl = "<your_url>";
String query = "?" + "<add_your_params_here>";
URL url = new URL (mainUrl + query);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// If you want to process the response you have to do something the the in InputStream. But ommiting it here, as you said you won't use the response.
}
catch (FileNotFoundException fnf){
Log.e("Incorrect Url", "Resource was not found");
}
catch (Exception e){
}
And remember to add the INTERNET permission for your Android Manifest xml file: android.permission.INTERNET
Check this response for adding internet permissions: What permission do I need to access Internet from an android application?
Use URLConnection for this.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am asking this because I am beginner in android development.
I am doing a core-banking application, so I used JSON Parser class to connect with REST Web-Service,
JSONParser Class is,
package com.anvinsolutions.digicob_custmate;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;// = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder(); // add this line
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
and i am confused if this method have any problem with Security,performance?
i didn't try any Libraries till now, i just used this JSONParaser Class. i think its easy to work with a JSONParser Class..
WHICH ONE TO USE?
thank you in advance! ;)
You never use JSonParser class to connect to a Web service. From your code, looks like you are using Vanilla HttpURLConnection class for connecting to service and using the JSonParser class to parse the result which is good and simple if you only have a couple of web requests to make in your application.
However since you said, it's banking application, you might have to think about scalability, multiple requests and stuffs like that. You could well try to handle them by yourself but the suggested way would be to use one of the tried and tested network libraries available for Android. Retrofit and Volley are two such and there are many more. The choice of the library to use is based on your use cases.
#AJay has already pointed to a page for comparison. Have a look.
Onto your next thing, about the parsing, performance is one of the key factors. Have a look at the below link for the options you have - http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
I would say GSon is pretty good among all. We use it extensively in our in-house products.
You can use GsonParser by Google.https://github.com/google/gson
Hello you can use any of these 3 libraries they both are equally good in performance. Check this link, it will help you. Happy learning.
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
If you have a deal with REST service, the easiest way is to use Retrofit library: https://square.github.io/retrofit/
With Retrofit you do not need to implement http calls and it automatically parses/creates json.
If you need more flexibility, I suggest using OkHttp library http://square.github.io/okhttp/, which is much simpler than pure HttpUrlConnection in combination with Gson lib https://github.com/google/gson for json parsing/creating.
I'm making an app which let people login, sign in, sign up, write something and save it to database.
So I decided to chose Restful Api with Slim Framework. I publish it in my host and test by extension of google chrome call Advanced Rest Client. Everything like login ,signin, sign up, wite something, update it, delete it.. work fine.
For example:
I log in with information:
email: stark#gmail.com
password: abc
then the result is something like that.
{
error: false
name: "Kien"
email: "nguyenkien1402#yahoo.com"
apiKey: "fc2aee103c861026cb53fd8920b10adc"
createdAt: "2015-06-24 00:28:01"
}
But when I used it in my android app. I cannot connect and get information by JSON.
Please tell my how to solve this problem.
Thank you.
Sorry about my english, it's not native english.
To connect to the restful API, the following steps you have to do
give internet access
have to do http connection
have to to take stream input
Give Internet Access
to give internet access to the app we have to add this piece of code in the file " AndroidManifest.xml"
<uses-permission android:name="android.permission.INTERNET"/>
To do the second and third step we have to create a new java class as when we are connecting to the restful API, it will run in the background and MainActivity does not allow the background task.
Let say we create a new java class "fetchData" to get data from the API.
to do the remaining task we have to use this piece of code
URL url = new URL(API ADDRESS);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
now you get the JSON file using the "Bufferedreader.readLine()"
then the class file looks like this
import android.os.AsyncTask;
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;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data ="";
String dataParsed = "";
String singleParsed ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/k3p10");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
for(int i =0 ;i <JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "Name:" + JO.get("name") + "\n"+
"email:" + JO.get("email") + "\n"+
"Error:" + JO.get("error") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
from the JSON array, you can extract everything from the JSON you get from the API. then you can use the information as per your requirement.
If your url is generating json response, then you have to read that.
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString(); //here is your response which is in string type, but remember that the format is json.
}
Then convert your response to json:
JsonObject obj = new JsonObject(response);
I solved it.
It up to my class about CRUD JSON.
Thank you.
I have looked at several APIs for acquiring restaurant menu for a particular location and determined that Locu API works best for me.
I was trying the basic example listed on locu website:
curl -X POST https://api.locu.com/v2/venue/search/ -d '{"fields":["name","menu_items","location","categories","description"],"menu_item_queries":[{"price":{"$lt":6},"name":"burrito"}],"venue_queries":[{"location":{"locality":"San Francisco"}}],"api_key":"MY_API_KEY"}'
Where, MY_API_KEY is the API_KEY that I received when I signed up.
As long as I include "menu_items" parameter, I keep getting the response:
{"status": "error", "http_status": 400, "error": "The requested \"menu_items\" field is either invalid or your account does not have permissions to access it."}
I did not come across any documentation regarding what I need to do in order to get the permissions for querying "menu_items". If anyone could point me in the right direction, I will really appreciate that.
I have already gone through some relatively old questions on here and they did not address this particular issue.
Also, there doesn't seem to be a tag for Locu api here. I am going to try and tag the question with some generic tags. Please excuse me for that.
I know this is an old question, but I've found that the solution is to request the "menus" field in a venue search. The API will return the "menu_items" as sub-objects of the menus.
`
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try{
String result;
URL url = new URL("https://api.locu.com/v1_0/venue/search/?api_key=" +apiKey);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);}
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}`
I am working on a computer that is joined with server in LAN.proxy is used to access internet in my computer, now i am doing project on consuming php web services which give JSON as output.i have made a app for it but it gives blank response,i have read one of the stack overflow question answer that say that it is because of proxy.
should i have to set proxy setting in my application.
And how can i set proxy for this problem.
i have set the proxy by this step
Click on Menu
Click on Settings
Click on Wireless & Networks
Go to Mobile Networks
Go to Access Point Names
Here you will Telkila Internet, click on it.
In the Edit access point section, input the "proxy" and "port"
Also provide the Username and Password, rest of the fields leave them blank
internet is working in emulator,but still project display nothing.
this is my code
package com.example.jsonexaple2;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
public class Jsonexaple2 extends Activity {
String archiveQuery = "http://www.archive.org/advancedsearch.php?q=Lotus&fl[]=date&fl[]=format&fl[]=identifier&fl[]=mediatype&fl[]=title&sort[]=createdate+desc&sort[]=&sort[]=&rows=10&page=1&output=json&callback=callback&save=yes";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jsonexaple2);
InputStream in = null;
String queryResult = "";
try {
URL url = new URL(archiveQuery);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect();
in = httpConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int read = 0;
int bufSize = 512;
byte[] buffer = new byte[bufSize];
while(true){
read = bis.read(buffer);
if(read==-1){
break;
}
baf.append(buffer, 0, read);
}
queryResult = new String(baf.toByteArray());
} catch (MalformedURLException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
} catch (IOException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
JSONObject jObject;
try {
jObject = new JSONObject(queryResult.replace("callback(", "")).getJSONObject("response");
JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i < 10; i++) {
if (docsArray.getJSONObject(i).optString("mediatype").equals("etree")) {
String title = docsArray.getJSONObject(i).optString("title");
String identifier = docsArray.getJSONObject(i).optString("identifier");
String date = docsArray.getJSONObject(i).optString("date");
System.out.println(title + " " + identifier + " " + date);
}
}
} catch (JSONException e) {
// DEBUG
Log.e("DEBUG: ", e.toString());
}
}
}
Yes you have to. Once, I had the same problem with the emulator. I searched on Google and I found these two blogs that are nice.
gitshah
twozao
Hope that it will help you.
I'm trying to download some content using the URL class with a given link that comes from the server.
My code to download is it:
URL url = new URL(downloadUrl);
InputStream stream = url.openStream();
byte[] content = new byte[stream.available()];
stream.read(content);
stream.close();
But when running I got the following exception:
java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:604 0xaf076228:0x00000000)
at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
...
The link I was using is something like:
https://contentserver.com/d/761/34/215656/5de1a41ea3bc9c81978af95ed19b03286f64d9a3
I know if I enter it on browser it donwload an File, I want download the same file throught Java.
Thanks
Code to read data from the https url in java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.*;
import java.security.Security;
import java.util.Properties;
public class UseHttps {
public static void main(String argv[]) {
String fullURL = "https://fortress.wa.gov/lni/bbip/detail.aspx?License=SIBLUCL004C5";
try {
URL page = new URL(fullURL); // Process the URL far enough to find the right handler
URLConnection urlc = page.openConnection();
urlc.setUseCaches(false); // Don't look at possibly cached data
System.out.println("Content-type = " + urlc.getContentType()); // See what's here
System.out.println("Content-length = " + urlc.getContentLength()); // See how much of it there is
// Read it all and print it out
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String buffer = "";
while (buffer != null) {
try {
System.out.println(buffer);
buffer = br.readLine();
}
catch (IOException ioe) {
ioe.printStackTrace();
break;
}
}
}
catch (MalformedURLException mue) {
System.out.println(fullURL + " is not a URL that can be resolved");
}
catch (IOException ie) {
ie.printStackTrace();
}
}
}
Marcos,
this might be completely irrelevant, but... I was getting the same error...
abort: error: _ssl.c:490: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
... trying to do an "hg clone" on my bitbucket.org mercurial repo..., I was trying to connect to bitbucket over https from the windows command line... it turned out that I was supplying the incorrect password to my proxy...
While I am not sure about your SSL error, the way you are reading data is most likely NOT what you want. InputStream.available() is not the amount of data in the stream. The stream is by definition "unbounded", and it is over only when it is over. InputStream does not know how many bytes it has. Method available() simply tells you how many bytes can be read without blocking on IO.