HTTP error 400 Bad Request when POSTing JSON data over HttpURLConnection - java

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

Related

Adding a token to a http for AWS api gateway

I'm using the code below to create a http request to my amazon AWS api gateway with an object (mp3Base64) as its content. However, it needs to have the authorization token attached. Can anyone explain how this is done and show an example? Any help is gratefully received. Thanks.
public String executePost(String targetURL, Mp3Base64 mp3Base64) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String mp3Base64Json = mapper.writeValueAsString(mp3Base64);
URL obj = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(mp3Base64Json.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("base64=" + mp3Base64Json);
wr.flush();
wr.close();
//Get Response
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + targetURL);
System.out.println("Post parameters : base64 =" + mp3Base64Json);
System.out.println("Response Code : " + responseCode);
InputStream is = connection.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}

How to pass JSON body in HTTP Put in JAVA

Can someone explain me how to pass JSON parameter in request body.
I am using HttpURLConnection to create the connection, as below:
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");
JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
How can I put set the req body here?
For specifying the body of your request:
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()

HttpUrlConnection 403-forbidden error Android

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" />

400 BadRequest while loginning in to website on Android

whenever I try to login to a website on my app I recieve a 400 BadRequest error. But when I do the same with a normal javaprogramm it works fine.
The login-methode:
public void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "www.XXX.de");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://XXX.de/YYY/");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
Log.w("App", "sendPost: ResponseCode: " + conn.getResponseCode());
responseCode = conn.getResponseCode();
james.setResponseCode_SendPost(responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} // end of sendPost
Before I start sendPost() I always download at first the page (without BadRequest):
public String getPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
conn.setHostnameVerifier(hostnameVerifier);
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
james.setResponseCode_GetPageContent(conn.getResponseCode());
int x = conn.getResponseCode();
Log.w("App", "ResponseCode: " + x);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + "\r\n");
}
in.close();
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
} // end of getPageContent
I found the mistake by myself
The OutputStream method writeBytes() has to be
wr.writeBytes("request=" + postParams);
instead of
wr.writeBytes(postParams);

Google ClientLogin authentication

I try make authentication using ClientLogin
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Email", "testonly%2Ein%2E2011%40gmail%2Ecom");
connection.setRequestProperty("Passwd", "mypass");
connection.setRequestProperty("accountType", "HOSTED");
connection.setRequestProperty("service", "apps");
connection.connect();
But I get Error=BadAuthentication. How I should correct my code?
You should set the proper application/x-www-form-urlencoded Content-type and use the OutputStream to write the POST body.
//Open the Connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// Form the POST parameters
StringBuilder content = new StringBuilder();
content.append("Email=").append(URLEncoder.encode(youremail, "UTF-8"));
content.append("&Passwd=").append(URLEncoder.encode(yourpassword, "UTF-8"));
content.append("&service=").append(URLEncoder.encode(yourapp, "UTF-8"));
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
// Retrieve the output
int responseCode = urlConnection.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
See this example to handle the result to get the auth token.

Categories