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;
}
}
Related
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";
PHP file is working fine. i don't seem to find the problem in this code. Why do i get that exception ? Is there any error in the outputStream ? is there another method that i can use to pass/get the data ?
#Override
protected String doInBackground(String... params) {
String email = params[0];
String password = params[1];
String data="";
int tmp;
try {
URL url = new URL("http://10.0.3.2/magasin/login.php");
String urlParams = "email="+email+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (Exception e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
String con=null,err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
con = user_data.getString("con");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Toast.makeText(ctx, err+"", Toast.LENGTH_SHORT).show();
}
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?
I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
I am getting a server side json response to load my menu, I tried twice and it gave this error message (the Error parsing data org.json.JSONException).
the reason for that is I'm getting the response partially, in both attempts i got different responses as shown in the images. i think I'm not getting the complete json response, getting only partial response. what should I do to get the complete response.
this is my code
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
try {
path = "http://xxxxxxxxxxxxxxxxxxx";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("CetegoryCode"), "P");
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
this is the image
If your response is returning JsonArray thn need to set tht response string jsonarray. create instance of jsonarray and fill it up with the response.
if its normal get ws thn you can append parameters in url like query string
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
try {
// Append parameters with values eg ?CetegoryCode=p
String path = "http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p";
URL url = new URL(path);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
Content = sb.toString();
JSONArray jArray = new JSONArray(Content);
if (jArray != null)
Log.e("Data", "" + jArray.length());
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
}
catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
Try out below code to parse and get JSON response:
public static JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
json = convertStreamToString(stream);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 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;
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
Use getJSONFromUrl method as below in your code:
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
try {
responseJson = new JSONObject(response);
responseJson =getJSONFromUrl("http://xxxxxxxxxxxxxxxxxxx?CetegoryCode=p");
}catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}