Android HttpURLConnection POST not working - java

I have a problem with the parameters passed to an URL by POST. When in PHP i try to retrieve them it says that $_POST is empty:
<?php
require_once 'credentials.php';
$connection = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DATABASE);
$query = 'INSERT INTO ratings (disco, rating) VALUES (' .mysqli_real_escape_string($connection, $_POST["disco"]). ', ' . mysqli_real_escape_string($connection, $_POST["rating"]) . ')';
$result = mysqli_query($connection, $query);
echo json_encode($result);
mysqli_close($connection);
?>
And my Android code looks like this:
#Override
protected String doInBackground(String... params) {
String response = "";
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("disco", params[1]));
parameters.add(new BasicNameValuePair("rating", params[2]));
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getQuery(parameters));
writer.flush();
writer.close();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((line = br.readLine()) != null) {
response += line;
}
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
return response;
}
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();
}
What's wrong with this? Thanks in advance
Edit: updated code and still doesn't work.

"&disco="
Make that:
"disco="

Related

Android cannot read http post response from flask server

I just wrote a simple server with flask and send a http post requset to the server from an Android App. But I failed to read the response in the Android App. The app throw an exception:
My flask code is:
#app.route('/zsj',methods = ['POST'])
def show_data():
data = request.get_json()
print request.values #json.loads(data)#request.get_json()
#data = json
#print data
return "aaaa"#jsonify({'w':'u'})
My android App just use the HttpURLConnection class to send a post and get a respones from the server, which is expected as a string: 'aaaa'. We tried to read out the string but failed.
And my Android code is
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
// Connect to the server
URL url = new URL("http://ec2-35-164-172-186.us-west-2.compute.amazonaws.com:5000/zsj");
JSONObject postDataParams = new JSONObject();
// Display command
postDataParams.put("Weather", "email");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
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();
responseMessage = conn.getResponseMessage();
int responseCode=conn.getResponseCode();
responseCode2=responseCode;
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
// jtest=conn.getInputStream().read(data);
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
StringBuffer sb = new StringBuffer("");
String line="";
StringBuffer sb2 = new StringBuffer("");
// in.readLine();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
// jtest="abc";
// jtest=sb.toString();
while((line = er.readLine()) != null) {
sb2.append(line);
break;
}
in.close();
er.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
My App code just throw an exception at
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
Anyone knows how to solve the problem

HttpURLConnection - Response Code: 400 (Bad Request) Android Studio -> xserve

So I'm trying to connect to our database via Xserve, AT the moment I'm trying to access the token for the user. I'm using the correct username and password along with the context type and grant type; I know this because I've tried the same POST method via googles postmaster extension. For whatever reason when I try the same thing on Android, at least what I think is the same, it gives me a 400 response code and doesn't return anything.
Here's the code used to connect:
private HttpURLConnection urlConnection;
#Override
protected Boolean doInBackground(Void... params) {
Boolean blnResult = false;
StringBuilder result = new StringBuilder();
JSONObject passing = new JSONObject();
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// set up parameters to pass
passing.put("username", mEmail);
passing.put("password", mPassword);
passing.put("grant_type", "password");
// add parameters to connection
OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(passing.toString());
// If request was good
if (urlConnection.getResponseCode() == 200) {
blnResult = true;
BufferedReader reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
//JSONObject json = new JSONObject(builder.toString());
Log.v("Response Code", String.format("%d", urlConnection.getResponseCode()));
Log.v("Returned String", result.toString());
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return blnResult;
}
I haven't stored the result into the JSONObject yet as I'll use that later, but I expected some kind of output via the "Log.v".
Is there anything that stands out?
try {
URL url = new URL("http://xserve.uopnet.plymouth.ac.uk/modules/INTPROJ/PRCS251M/token");
parameters = new HashMap<>();
parameters.put("username", mEmail);
parameters.put("password", mPassword);
parameters.put("grant_type", "password");
set = parameters.entrySet();
i = set.iterator();
postData = new StringBuilder();
for (Map.Entry<String, String> param : parameters.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
postDataBytes = postData.toString().getBytes("UTF-8");
// set up connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.getOutputStream().write(postDataBytes);
// If request was good
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
}
Log.v("Login Response Code", String.valueOf(urlConnection.getResponseCode()));
Log.v("Login Response Message", String.valueOf(urlConnection.getResponseMessage()));
Log.v("Login Returned String", result.toString());
jsonObject = new JSONObject(result.toString());
token = jsonObject.getString("access_token");
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
if (token != null) {
jsonObject = driverInfo(token);
}
}
this works, although I've moved it to it's own function now.
changed the input type to a HashMap

I am getting 411 HTTP Error while using POST method in Java

I am facing a problem while using POST Method in Java nowadays. I am receiving
Exception in thread "main" java.lang.RuntimeException: Server returned HTTP response code: 411 for URL.
I couldn't find any available document anywhere. None of them were useful. How do I fix it?
My code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class req {
public static void main(String[] args) {
sendPostRequest(requestURL);
}
private static String sendPostRequest(String requestUrl) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
byte[] data = requestUrl.getBytes("UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
connection.setRequestProperty("Authorization", "Basic " + "usename:password");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return jsonString.toString();
}
}
Perfectly working method:
public 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 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();
}
If you are returning a JSON in your response:
public JSONObject getPostResult(String json){
if(!json.isEmpty()) {
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON_ERROR", "Error parsing data " + e.toString());
}
}
return jObj;
}
If you are still having trouble, maybe this will help. I did not test, machine does not have java installed.
You should also set all other headers that you need.
public static String PostRequest(String requestUrl, String username, String password) {
StringBuilder jsonString = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection)url.openConnection();
byte[] authData = Base64.encode((username + password).getBytes());
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + new String(authData));
connection.setRequestProperty("Content-Length", String.valueOf(authData.length));
try (DataOutputStream writer = new DataOutputStream(connection.getOutputStream())) {
writer.writeBytes("REPLACE ME WITH DATA TO BE WRITTEN");
writer.flush();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String data = null;
while ((data = reader.readLine()) != null) {
jsonString.append(data);
}
}
} catch (IOException ex) {
//Handle exception.
} finally {
if (connection != null)
connection.disconnect();
}
return jsonString.toString();
}
You should send empty data in body if you are using post method.
For example if you are using json data you need to send "{}"
public void Post() throws Exception {
StringBuffer d = new StringBuffer();
String da = "ClearanceDate=2020-08-31&DepositeDate=2020-08-31&BankTransactionNo=UATRYU56789";
URL url = new URL("https://abcd/AddReceipt?" + da);
byte[] postDataBytes = ("https://abcd/AddReceipt?" + da).toString()
.getBytes("UTF-8");
System.out.println("Data--" + postDataBytes);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// con.setRequestProperty("User-Agent",
// "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",
String.valueOf(postDataBytes.length));
con.setRequestProperty(
"Authorization",
"Bearer "
+ "o731WGgp1d913ZOYivnc55yOg0y1Wk7GsT_mnCUKOJf1VChYOdfRjovAxOhyyPKU93ERue6-l9DyG3IP29ObsCNTFr4lGZOcYAaR96ZudKgWif1UuSfVx4AlATiOs9shQsGgb1oXN_w0NRJKvYqD0LLsZLstBAzP1s5PZoaS9c6MmO32AV47FUvxRT6Tflus5DBDHji3N4f1AM0dShbzmjkBCzXmGzEDnU6Jg1Mo5kb884kParngKADG5umtuGbNzChQpMw_A0SyEYaUNh18pXVmnNhqM3Qx5ZINwDEXlYY");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);
int status = con.getResponseCode();
System.out.println("Response status: " + status + "|"
+ con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
System.out.print("Raw Response->>" + d);
}

Can't run HTTP request when call it from click event on JForm button while it works fine when call it from main Class

I have method to call web service of signin and it is working fine when call it from main() method ... but when call it from event handler of button on JFrame I got : Server returned HTTP response code: 500 for URL: http://localhost/postrec/index.php/api/Site/Login Error.
this is happen at the line code :Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
the Method is :
public boolean doLogin(String username, String password) throws MalformedURLException{
try{
URL url = new URL("http://localhost/postrec/index.php/api/Site/Login");
Map<String,Object> params = new LinkedHashMap<>();
params.put("username", username);
params.put("password", password);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String responseStr = "";
for (int c; (c = in.read()) >= 0; responseStr = responseStr + (char)c);
JSONObject jsonObject = new JSONObject(responseStr);
return (jsonObject.getString("code").equals("200"));
}catch(JSONException | MalformedURLException | UnsupportedEncodingException e){
throw new MalformedURLException(e.getMessage());
}catch(IOException e){
System.out.println(e.getMessage());
}
return false;
}

How to read an HTTP input stream?

The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}

Categories