Can't POST data to site using HttpURLConnection on Android - java

I'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>

Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().

remove this,
c.setRequestProperty("Content-length", "0");

Related

Fetching array from json not working

Currently I am working with a project where I need to get some data from remote server as JSON then need to extract array. Here I am getting data successfully, But problems are near while loop.
I am getting data from remote server successfully.
For example my remote url giving output as:
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`
Code
try {
ur = "http://localhost/getsample.php";
URL url = new URL(ur);
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;
}
data = data.replace("null", "");
JSONArray JA = new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
idArray = idArray + JO.get("id") + ",";
amountArray = amountArray + JO.get("amount") + ",";
course_codeArray = course_codeArray + JO.get("course_code") + ",";
courseArray = courseArray + JO.get("course") + ",";
contentArray = contentArray + JO.get("content") + ",";
thumbArray = thumbArray + JO.get("thumb") + ",";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
The data you get from the server are at JSON format but they are not Array . this is an object ,
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}
So you have to loop inside the json object like
for (var key in jsonResponse) {
if (jsonResponse.hasOwnProperty(key)) {
console.log(key + " -> " + jsonResponse[key]);
}
}
EDIT : If you have multiple Objects inside an object you have to loop inside them ( external for) like for(var i in JsonObject)
Your Code is should be like According to your current Response
try{
JSONObject jso = new JSONObject(data);
amountArray =jsonObject.getString("amount");
course_codeArray =jsonObject.getString("yourNextKey");
courseArray = jsonObject.getString("yourNextKey");
contentArray = jsonObject.getString("yourNextKey");
thumbArray = jsonObject.getString("yourNextKey");
}
catch (JSONException e) {
e.printStackTrace();
}

Pass php var or string to java. Android Studio

I'm not really sure how to do go about passing a variable from PHP to Java. I'd like to do the business logic in Java. I'd like to pass a variable $result from the PHP script dupCreateAccount.php.
<?php
require "db.php";
if(mysqli_num_rows($resultName) > 0 || mysqli_num_rows($resultEmail) > 0)
{
$result = "ex";
}
else
{
$result = "b";
}
if( count_chars($password) < 6)
{
$result = "bP";
}
echo (string) $result;
?>
This the php code. When I echo the results I can see the strings when running the android emulator.
protected String doInBackground(String... voids) {
String type = voids[3];
String checkUsername_url = "http://localhost/dupCreateAccount.php";
if(type.equals("Validate"))
{
try {
String user = voids[0];
String email = voids[1];
String password = voids [2];
URL url = new URL(checkUsername_url);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream outputStream = httpConn.getOutputStream();
BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_date = URLEncoder.encode("user", "UTF-8") + "="+URLEncoder.encode(user,"UTF-8") + "&"
+ URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8") + "&"
+ URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
buffWriter.write(post_date);
buffWriter.flush();
buffWriter.close();
outputStream.close();
InputStream is = httpConn.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
String result = "";
String line;
while((line = bf.readLine()) != null)
{
result += line;
}
bf.close();
is.close();
httpConn.disconnect();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
if(result.equals("b"))
result = "bad username or email";
if(result.equals("bP"))
result = "bad password";
alert.setMessage(result + " on Crack Execute here");
alert.show();
}
What I was thinking was that when I return the variable result in PHP it gets sent too the OnPostExecute method. But I don't that's right. I'm not sure what step I'm missing .
EDIT: So the php result gets passed to java. But the problem i'm having is messing with the String result after it's passed. In the OnPostExecute method the equals method doesn't do anything.

Read any Language String from Google Translator in Android

I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.

How to send a json string as an input parameter to a POST request in android

and facing a problem in sending the JSON string to a POST request.
This is my URL: http://172.25.183.183:8080/JIRAservice/rest/runquery
Key : query
Value:
{ "jql": "project=<projectkey>",
"startAt": 0,
"maxResults": 100,
"fields": [
"summary",
"customfield_10006",
"status",
"description"
]
}
Where <projectkey> is the value stored in the shared preferences please help
this is my code
try{
TextView op=(TextView) findViewById(R.id.resp);
URL url=new URL("http://172.25.183.183:8080/JIRAservice/rest/runquery");
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setRequestMethod("POST");
String projectKey=Home.savedid;
JSONObject jsonParam = new JSONObject();
jsonParam.put("query", " "{ \"jql\": \"project=" + projectKey + "\", \"startAt\": 0, \"maxResults\": 100, \"fields\": [\"summary\",\"customfield_10006\", \"status\", \"description\"] }"");
how to send the parameters??
conn.setDoOutput(true);
DataOutputStream dbstrm=new DataOutputStream(conn.getOutputStream());
dbstrm.flush();
dbstrm.close();
int respnse=conn.getResponseCode();
String output="Request URl"+url;
output+=System.getProperty("line.separator");
output+=System.getProperty("line.separator")+"Response Code"+respnse;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line= "";
StringBuilder respop=new StringBuilder();
while((line=br.readLine())!=null){
respop.append(line);
}
br.close();
output +=System.getProperty("line.separator")+respop.toString();
op.setText(output);
}catch(MalformedURLException ae){
ae.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try{
URL url=new URL("http://172.25.183.183:8080/JIRAservice/rest/runquery");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String projectKey=Home.savedid;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query"," { \"jql\": \"project=" + projectKey + "\", \"startAt\": 0, \"maxResults\": 100, \"fields\": [\"summary\",\"customfield_10006\", \"status\", \"description\"] }"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int respnse=conn.getResponseCode();
String output="Request URl"+url;
output+=System.getProperty("line.separator");
output+=System.getProperty("line.separator")+"Response Code"+respnse;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line= "";
StringBuilder respop=new StringBuilder();
while((line=br.readLine())!=null){
respop.append(line);
}
br.close();
output +=System.getProperty("line.separator")+"IssueList from API"+respop.toString();
System.out.println("IssueList"+ output);
String respfield=resp(respop.toString());
System.out.println(" response"+ respfield);
}catch(MalformedURLException ae){
ae.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
getQuery() method
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}

Google Distance Matrix not getting distance

I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}
First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.

Categories

Resources