HTTP Post via Android-Java does not work - java

I 'm using the following code to post value variables to a server:
protected String doInBackground(String... params) {
try{
URL url= new URL(params[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data= URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
post_data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
Here is the async-task call:
BackgroundWorker backgroundWorker= new BackgroundWorker(this);
backgroundWorker.execute("http://...", "somename", "somesurname");
The code runs fine (no errors), however I'm not able to see any data in my database (.php is also working correctly-double checked).
What could be the issue here?

I would suggest using volley instead, here's a good and easy tutorial: http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
But here is how I used httpURLConnection:
public String executePost() {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(/*URL HERE*/);
String urlParameters = "/*THE PARAMS. YOU KNOW THIS ;) */";
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Related

post request in android studio like curl

I have a question how to implement a post request in java in android studio if I have a valid request using curl:
'curl.exe anyValidUrl -d "911/21.10.2020/15.45" -H "Content-Type: text/plain"'
When sending data to the server, error 500 takes off.
Most likely I am sending data in the wrong form, where am I wrong, please tell me.
The function in which I am sending data:
{
InputStreamReader isR = null;
BufferedReader bfR = null;
StringBuilder sbRes = new StringBuilder();
HttpURLConnection urlConnection = null;
String strBody = "911/21.10.2020/15.45";
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Length","" + Integer.toString(strBody.getBytes().length));
urlConnection.addRequestProperty("Content-Type","text/plain");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(strBody);
wr.flush();
wr.close();
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( urlConnection.getRequestMethod());
if (HttpURLConnection.HTTP_OK == urlConnection.getResponseCode()) {
isR = new InputStreamReader(urlConnection.getInputStream());
bfR = new BufferedReader(isR);
String line;
while ((line = bfR.readLine()) != null) {
sbRes.append(line);
}
}
else{
return (String.valueOf(urlConnection.getResponseCode()));
}
return sbRes.toString();
}

HttpUrlConnection working with one url but not with another url

One URL works well with HttpUrlConnection in asynctask but another still posting and requesting the same data crashes the app.
but the same server directory has other files and they DoInput and DoOutput successfully
#Override
protected String doInBackground(String... params)
{
try {
getter_url = new URL("this one returns successfully");
getter_url0 = new URL("this one just crashes the app");
} catch (MalformedURLException e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
afbah= params[0];
if (afbah.equals("whfiavbkjnfdl"))
{
String kbfisy= params[1];
try
{
try {
httpURLConnection = (HttpURLConnection) getter_url0.openConnection();
}catch (Exception e){
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
return e.toString();
}
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("gisyfgb", "UTF-8") + "=" + URLEncoder.encode(kbfisy, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
StringBuilder ANSWER = new StringBuilder();
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
ANSWER.append(line).append("\n");
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
I really really can't understand why the two URL's will be acting differently
On postman API it results success the two URL's but the HttpUrlConnection results success for the first url and error for the second one.
please ask me for any information you need to help
What are the example URLs?
It is possible that the URL is not parsed correctly, try this approach:
URL url = new URL(urlString);
URI uri = new URI(
url.getProtocol(),
url.getUserInfo(),
url.getHost(),
url.getPort(),
url.getPath(),
url.getQuery(),
url.getRef()
);
HttpURLConnection connection = (HttpURLConnection) new URL(uri.toASCIIString()).openConnection();

Android app to transfer data

I am sending data to a server via HTTPUrlConnection. It is received on the server side with PHP code and inserted into a MySQL database. Everything is functioning as intended. The issue is that it using a lot of data to do it. The info I am sending is in the variable unitData which is between 80 and 200 characters long. The data reportedly being used is 3K to 8K of data each transfer. This seem like a lot of overhead to move 200 bytes. I need this to be as small as possible for my application to work, preferably under 500 bytes. Is there a way to tweak HTTPUrlConnection or should I be using Websockets or something else entirely?
class dataSender extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String unitData = params[0];
try {
URL url = new URL("https://www.website.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(10000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//connection.setRequestProperty("Content-Length", "" + test.length());
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes ("mydata="+unitData);
wr.flush ();
wr.close ();
//Get Response
int responseCode = connection.getResponseCode();
StringBuffer response = new StringBuffer();
if(responseCode == 200) {
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
else{
response.append("Error:");
response.append(responseCode);
}
connection.disconnect();
return response.toString();
//return "nada";
} catch (Exception e) {
//Toast.makeText(getApplicationContext(), "exception:"+e, Toast.LENGTH_SHORT);
return e.toString();
}
}
}

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);
}

Error 86 This method requires a GET or HEAD using Bearer token on Twitter Rest API 1.1 using Java in AppEngine

I have my bearerToken and userID as per Twitter instructions https://dev.twitter.com/docs/auth/application-only-auth and I want t get a list of followers.
I'm getting error 86, which isn't on the list of error codes https://dev.twitter.com/docs/error-codes-responses
Any pointers would be appreciated.
public String getTwitterFriends(String userID, String bearerToken) {
// Use App Bearer token to get public friends
String answer = "";
String param = "count=5000&cursor=-1&user_id=" + userID;
HttpURLConnection connection = null;
try {
// String request =
// "https://api.twitter.com:443/1.1/friends/ids.json?" + param;
String request = "https://api.twitter.com/1.1/friends/ids.json?"
+ param;
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
System.setProperty("http.keepAlive", false ? "true" : "false");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
// connection.setRequestProperty("Host", "api.twitter.com" +
// ":443");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Authorization", "Bearer "
+ bearerToken);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("User-Agent", "UnhappyChappy");
// connection.setRequestProperty("Accept-Encoding", "gzip");
// connection.setRequestProperty("Content-Length", "" +
// Integer.toString(param.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
// wr.writeBytes(param);
wr.flush();
wr.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
StringBuilder str = new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
str.append(line);
}
reader.close();
connection.disconnect();
answer = str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(answer);
return answer;
}
It was the way I issued the GET. I had to go to a lower level on App Engine and use FetchOptions This worked for me, hopefully it will help someone else.
URL url = new URL(request);
HTTPRequest req = new HTTPRequest(url, HTTPMethod.GET);
req.addHeader(new HTTPHeader("Authorization", "Bearer " + bearerToken));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(req);
System.out.println(new String(response.getContent()));

Categories