HttpUrlConnection 403-forbidden error Android - java

Below is my code snippet. 403 error coming. COuld anyone please give the solution to overcome this 403 error. This is the post JSON request.
#Override
protected String doInBackground(Void... voids) {
try {
trustAllHosts();
URL url = new URL(postUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userCredentials = username+":"+password;
String basicAuth = "Basic " + new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("X-CSRF-TOKEN",token);
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
PostRootObject postRootObject = new PostRootObject();
Gson gson = new GsonBuilder().create();
String json = gson.toJson(postRootObject);
JSONObject jsonObject = new JSONObject(json);
Log.e("Json object",""+jsonObject);
DataOutputStream os = new
DataOutputStream(conn.getOutputStream());
// os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
os.writeBytes(jsonObject.toString());
os.flush();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}

Maybe you are missing this line from your manifest file:
<uses-permission android:name="android.permission.INTERNET" />

Related

HTTP error 400 Bad Request when POSTing JSON data over HttpURLConnection

I am trying to connect to sharepoint to get the access token.I am using below code to call the api but getting 400 bad request.It's working with postman.
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// conn.setRequestProperty("Accept", "application/json;");
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");
JSONObject obj2 = new JSONObject();
obj2.put("grant_type", mygranttype);
obj2.put("client_id", clientid);
obj2.put("client_secret", secret);
obj2.put("resource", resource);
// System.out.println(conn.getHeaderFields());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(obj2.toString());
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I tried below options:
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");

Post request java http connection 403 forbidden error

I try to send a post request using a java program, I tested the post request URL in postman software, its working fine and post-operation are successful. But when I tried to replicate the same using java program with Http Url connection it pops out the 403 status as Forbidden.
Java code
public class Alexacreate {
public static void main(String Arg[]) throws MalformedURLException, IOException, JSONException {
JSONObject productjson = new JSONObject();
productjson.put("InternalID", "P987240");
String input = productjson.toString();
URL urlForUPdate = new URL("https://my348141.sapbydesign.com/sap/byd/odata/cust/v1/alexatest/MaterialCollection");
HttpURLConnection conn = (HttpURLConnection) urlForUPdate.openConnection();
conn.setRequestProperty("Authorization", "Basic RGV2VXNlcjAxOldlbGNvbWUwMQ==");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("x-csrf-token", "mQG3DNW_MMwaoIyvaqgepg==");
conn.setDoOutput(true);
conn.setDoInput(true);
System.out.println(input);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.connect();
System.out.println(conn.getResponseMessage());
if (conn.getResponseCode() == 201) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String outPut;
while ((outPut = bufferedReader.readLine()) != null) {
}
System.out.println("Created");
} else {
System.out.println("Not created");
}
}
}

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

HTTP Post via Android-Java does not work

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

Log in to facebook using httpurlconnection

I'm trying to login to facebook using httpurlconnect. I think i need to get the cookie from facebook.com/ajax/bz and then pass it along with my login attempt but maybe not. The response just takes me back to the login page and I never log in. Can someone help me get this to log in?
I do not want to use the official API.
private String getRequestCookie() throws IOException {
// URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
/* URLConnection urlConn = null;
try {
urlConn = url.openConnection(currentProxy);
urlConn.connect();
} catch (IOException e) {
e.printStackTrace();
}*/
String cookies = "";
URL myUrl = new URL("https://www.facebook.com/ajax/bz");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
String headerName=null;
for (int i=1; (headerName = urlConn.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookies = cookies+cookieName+"="+cookieValue+"; ";
//cookieNameList.add(cookieValue);
System.out.println("da cookies:" + cookies);
return cookies;
}
}
// must have failed yo
cookies = "failed";
return cookies;
}
private String performJsonPost() {
try {
String cookies = getRequestCookie();
String query = "email=EMAILNAME%40EMAIL.com&pass=PASSWORD&lsd=AVrVVnf1&default_persistent=0&timezone=&lgnrnd=132329_hCSS&lgnjs=n&locale=tr_TR";
URL urls = new URL("https://www.facebook.com/login.php?login_attempt=1");
final HttpURLConnection conn = (HttpURLConnection)urls.openConnection();
final byte[] payloadAsBytes = query.getBytes(Charset.forName("UTF-8"));
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", "reg_fb_gate=https%3A%2F%2Fwww.facebook.com%2F; reg_fb_ref=https%3A%2F%2Fwww.facebook.com%2F; reg_ext_ref=deleted; Max-Age=0; datr=0aFzVK8Fu0Gl7M8cn_6TSqlZ");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "" + payloadAsBytes.length);
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
final DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(payloadAsBytes);
// outStream.write(payloadAsBytes);
outStream.flush();
outStream.close();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
/* catch (Exception e2) {
//inStream = conn.getErrorStream();
}*/
final StringBuilder response = new StringBuilder();
final byte[] buffer = new byte[1024];
int bytesRead;
//System.out.println(inStream.toString() + "WHAT ARE U SAYING BRO");
//while ((bytesRead = inStream.read(buffer)) > 0) {
//response.append(new String(buffer, "UTF-8").substring(0, bytesRead));
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
// inStream = conn.getInputStream();
}
return response.toString();
}catch (IOException e) {
e.printStackTrace();
return null;
}
// System.out.println("Response!:"+response.toString());
// return response.toString();
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
It doesn't matter that you want to do it; according to the Automated Data Collection Terms, it's not allowed. You app/server can be blocked. Don't do this. Instead, just use the Graph API and all documented features.

Categories