Android: Parse json using httpurlconnection [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am using httpurlconnection and I can't find understandeble way to parse my json.
attribute output return this json {"value":"SUCCESS"}
but how to parse the json?
code
protected Void doInBackground(String... params) {
String ue=params[1];
try {
//final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("my url return json ");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "e="+ue;
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
final StringBuilder output = new StringBuilder("Request URL " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//output;
try {
JSONObject json = new JSONObject(output.toString());
message = json.optString("value");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(register.this,"output: "+output, Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
progress.dismiss();
}
if there is any dependences that I should to add to gradel.Please, let me know! thank you in advance

Simplest way:
try {
JSONObject json = new JSONObject(output); // output string
String message = json.optString("value"); // SUCCESS
} catch (JSONException e) {
e.printStackTrace();
}
But I would recommend to use Gson.

Related

How can I get youtubeVideo Title from URL for android studio?

I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";

HTTP response not giving output

I am working on an application that interacts with a room security control device.
I want to get devices information from API. I am using HttpUrlConnection and POST method. It hits the API and I get 200 OK response but I get the out
"{"json":{"control":{"cmd":"getdevice","uid":256}}} doesn't exist"
I have tried all the solutions from stackoverflow and other platforms but it's not giving the output.
Moreover I have tested this API on Postman and it's working there and giving the device information.
Here is the code:
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String username = "admin";
String password = "888888";
URL url = null;
try {
url = new URL("http://192.168.100.25/network.cgi");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("POST");
httpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setDoInput(true);
httpRequest.setDoOutput(true);
android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
httpRequest.addRequestProperty("Authorization", "Basic " + "YWRtaW46ODg4ODg4"); // This is auth bytecode
httpRequest.connect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjectControl = new JSONObject();
jsonObjectControl.put("cmd","getdevice");
jsonObjectControl.put("uid",256);
jsonObject.put("control",jsonObjectControl);
json.put("json", jsonObject);
String encodedData = URLEncoder.encode( json.toString(), "UTF-8" );
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpRequest.getOutputStream()));
writer.write(encodedData);
writer.flush();
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader
(new InputStreamReader(httpRequest.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
sb.append(line);
Log.i("Output line: ",sb.toString());
}
while(bufferedReader.readLine()!=null);
bufferedReader.close();
int responseCode = httpRequest.getResponseCode();
String resMsg = httpRequest.getResponseMessage();
String result = sb.toString();
Log.d("Output: ","--"+result);
Log.d("Response Code: "+responseCode, "!!");
Log.d("Response MSG ","--"+resMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Android: java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK

I have been working on the following code for a while.
the code worked for the 5.x version of my app but I can't get the code to work for Android version 6.x and higher.
public class PostAsync extends AsyncTask<String, Integer, Double> {
private Context _context = null;
public PostAsync(Context context) {
_context = context;
}
#Override
protected Double doInBackground(String... params) {
String serverResponse = postData(params[0]);
try {
JSONObject obj = new JSONObject(serverResponse);
String id = "";
JSONObject locationobj = obj.getJSONObject("X");
JSONObject response = locationobj.getJSONObject("Y");
id = response.getString("id");
Settings.idcode = id;
// Convert , to %2c, since we're working with a URI here
String number = Settings.number + Settings.code + "," + Settings.idcode; // %2c
_context.startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel://" + number)));
}
catch (Exception e) {
// TODO: Errorhandler
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
}
protected void onProgressUpdate(Integer... progress) {
}
// Send a POST request to specified url in Settings class, with defined JSONObject message
public String postData(String msg) {
String result = null;
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
URL url = new URL(Settings.webURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setChunkedStreamingMode(0);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestProperty("Content-Encoding", "identity");
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("TYPE", "JSON");
connection.setRequestProperty("KEY", "key");
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(msg);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMessage);
if(responseCode == HttpURLConnection.HTTP_OK){
is = new BufferedInputStream(connection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
try {
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
result = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
I get the following error
java.net.ProtocolException: Unexpected status line: HTTP/1.2 200 OK
Can someone tell me what I am missing?

HttpUrlConnection Forbidden access to Google Shortener URL

I have implemented a class to get a short url from a long url:
public class URLShortener {
private final static String TAG = "URLShortener";
private final static String ADDRESS = "https://www.googleapis.com/urlshortener/v1/url?key=API_KEY";
static JSONObject jObj = null;
static String json = "";
private String longUrl;
public URLShortener(String longUrl) {
this.longUrl = longUrl;
}
//public JSONObject getJSONFromUrl(String address,String longUrl) {
public JSONObject getJSONFromUrl() {
URL url;
HttpURLConnection urlConnection = null;
// Making HTTP request
try {
//Define connection
url = new URL(URLShortener.ADDRESS);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
//Define JSONObject
JSONObject dataSend = new JSONObject();
Log.d(TAG, "longURL: " + URLEncoder.encode(this.longUrl, "UTF-8"));
dataSend.put("longURL", URLEncoder.encode(this.longUrl, "UTF-8"));
//Send data
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(dataSend.toString());
wr.flush();
wr.close();
Log.d(TAG, "Data send");
Log.d(TAG, "ResponseCode: " + String.valueOf(urlConnection.getResponseCode()));
//Display what returns POST request
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
//System.out.println(""+sb.toString());
Log.d(TAG, "sb: " + sb.toString());
}else{
//System.out.println(urlConnection.getResponseMessage());
Log.d(TAG, "urlConnection.getResponseMessage(): " + urlConnection.getResponseMessage());
}
json = sb.toString();
Log.e("JSON", json);
// Parse the String to a JSON Object
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d(TAG, "UnsuppoertedEncodingException: " + e.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "Error JSONException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "IOException: " + e.toString());
}
// Return JSON Object
return jObj;
}
}
When I call the method getJSONFromUrl I've got always the same result ResponseCode = 403 (Forbidden).
What am I doing wrong?

pass parameters via http post method

I have two text boxes, 1 for username and the other for password.
I wanted to pass what the user enters into the edit texts with the post method
String request = "https://beta135.hamarisuraksha.com/web/webservice/HamariSurakshaMobile.asmx/getIMSafeAccountInfoOnLogon";
URL url;
try {
url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;");// boundary="+CommonFunctions.boundary
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
/*
* System.out.println("\nSending 'POST' request to URL : " +
* url); System.out.println("Post parameters : " +
* urlParameters);
*/
System.out.println("Response Code : " + responseCode);
InputStream errorstream = connection.getErrorStream();
BufferedReader br = null;
if (errorstream == null) {
InputStream inputstream = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(inputstream));
} else {
br = new BufferedReader(new InputStreamReader(errorstream));
}
String response = "";
String nachricht;
while ((nachricht = br.readLine()) != null) {
response += nachricht;
}
// print result
// System.out.println(response.toString());
return response.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
if i am getting your question correctly , you need to pass your parameters to a web service. in my case i have implemented a method to get the web service response by giving the url and the values as parameters. i think this will help you.
public JSONObject getJSONFromUrl(JSONObject parm,String url) throws JSONException {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
/*JSONObject parm = new JSONObject();
parm.put("agencyId", 27);
parm.put("caregiverPersonId", 47);*/
/* if(!(jObj.isNull("d"))){
jObj=null;
}
*/
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity body = new StringEntity(parm.toString(), "utf8");
httpPost.setEntity(body);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
/* String response = EntityUtils.toString(httpEntity);
Log.w("myApp", response);*/
} 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();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// JSONObject jObj2 = new JSONObject(json);
// 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;
}
this method take two parameters. one is the url, other one is the values that we should send to the web service. and simply returns the json object. hope this will help you
EDIT
to pass your username and password just use below code
JsonParser jp = new JsonParser(); // create instance for the jsonparse class
String caregiverID = MainActivity.confirm.toString();
JSONObject param = new JSONObject();
JSONObject job = new JSONObject();
try {
param.put("username", yourUserNAme);
job = jp.getJSONFromUrl(param, yourURL);

Categories

Resources