After running the post request with JSON I have HTTP Error 400 Bad request.
I think the problem is in the JSON string but I do not now how to fix it.
package Curl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
public class Http_Con {
private static HttpURLConnection connection;
public static void main(String[] args) throws IOException {
Http_Con connection = new Http_Con();
//call the getRequest method
connection.GetRequest();
//call the postRequest
connection.PostRequest();
}
public void GetRequest() {
BufferedReader reader;
String lines;
StringBuilder responseContent = new StringBuilder();
try {
//set the url
URL url = new URL("http://192.168.0.104:4041/iot/devices");
//open the connection
connection = (HttpURLConnection) url.openConnection();
//set the request method and timeout
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//set request properties(in this case headers)
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Fiware-Service", " myHome");
connection.setRequestProperty("Fiware-ServicePath", "/environment");
//get the response code(200 should be OK)
int status = connection.getResponseCode();
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
}
//print the response content(result)
System.out.println(responseContent.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public void PostRequest() throws IOException {
//set the url
String url = "http://192.168.0.104:4041/iot/devices";
URL obj = new URL(url);
//open the connection
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//set the method type(POST OR GET)
connection.setRequestMethod("POST");
//set hte request properties(headers etc.)
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Fiware-Service"," myHome");
connection.setRequestProperty("Fiware-ServicePath","/environment");
//make sure that will be able to write content to the connection output stream
connection.setDoOutput(true);
//Json formatted input string
String jsonInputString = "{\n" +
" \"devices\": [\n" +
" {\n" +
" \"device_id\": \"sensor01\",\n" +
" \"entity_name\": \"LivingRoomSensor\",\n" +
" \"entity_type\": \"multiSensor\",\n" +
" \"attributes\": [\n" +
" { \"object_id\": \"t\", \"name\": \"Temperature\", \"type\": \"celsius\" },\n" +
" { \"object_id\": \"l\", \"name\": \"Luminosity\", \"type\": \"lumens\" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//print the result
System.out.println(response.toString());
}
}
}
I Think you can use Fidder application to do something, which find Questions so fast. Due to 400 statusCode, Liking Cookie lost, params lost, request method lost .... trust think for you help!
I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and they need auth and date/time header. I am fairly new to java can anyone guide me?
This is the updated code which I with authentication and date/time header but now getting the below error.
UPDATED CODE
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
public class DuoAdminAPI {
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME); //RFC_1123 == RFC_2822
final String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
System.out.println(POST_PARAMS);
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
}
ERROR
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes
As I have read the documentation, the authorization is Basic:
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
For date is this:
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME); //RFC_1123 == RFC_2822
In their documentation they require RFC 2822 format. We already have declared RFC 1123 in DateTimeFormatter, which practically it is the same.
And this is the way you can add them in headers:
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
I have been told to execute this java program which is linked to a virtual number, when you run it, the output is a number code or whatever it is that i sent the number in sms.
I am using selenium and maven and also in the eclipse program and was told to use the testng plugin. They asked me to use #test annotations in an .xml file to execute it.
Im knew to programming and to be honest i have no idea how to write the xml file in order to run this and when i ask the person who told me to do this all they do is say google it and i have tried but i havent found anything.
the code is:
package utility;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.apache.commons.codec.binary.Base64;
//import sun.misc.BASE64Encoder;
public class APIcall {
// String MobileNo = ""; // virtual mobile no. (From message media)
private final String USER_AGENT = "Mozilla/5.0";
// Msg media Account:
// Password:
String name = ;
String password = ;
String authString = name + ":" + password;
//String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
String authStringEnc = new Base64().encodeBase64String(authString.getBytes());
static String URL = "https://api.messagemedia.com";
String getURI = "/v1/replies";
static String postURI = "/v1/replies/confirmed";
static Client client = ClientBuilder.newClient();
public Data getRequest() {
Response response = (Response) client.target(URL +
getURI).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + authStringEnc).get();
String body = response.readEntity(String.class);
// System.out.println("status: " + response.getStatus());
// System.out.println("headers \n: " + response.getHeaders());
System.out.println("body: \n" + body);
JSONObject json = new JSONObject(body);
JSONArray reply = (JSONArray) json.get("replies");
List<String> ids = new ArrayList<String>();
for (int idx = 0; idx < reply.length(); idx++) {
// ids.add(replyIds.get(idx).toString());
ids.add(reply.getJSONObject(idx).getString("reply_id"));
}
Assert.assertEquals(200, response.getStatus());
/*
* String OTPcode = (String) body.substring(body.lastIndexOf(' ') + 1); OTPcode
* = OTPcode.substring(0, 6).trim();
*/
String getContent = reply.getJSONObject(0).getString("content");
System.out.println(getContent);
String[] content = getContent.split(" ");
String code = content[content.length - 1];
// System.out.println("OTP code : " + code);
// System.out.println("List of replies : " + ids);
return new Data(code, ids, getContent);
//JSONException
}
public final class Data {
public String otp;
public List<String> list;
public String getContent;
public Data(String otp, List list, String getContent) {
this.otp = otp;
this.list = list;
this.getContent = getContent;
}
}
public void postRequest() {
/*
* Post request : Add reply ids recieved from GET request and pass it in body
* with POST request to confirm replies
*/
List<String> ids = getRequest().list;
String postStr = "{ \"reply_ids\":[";
for (String id : ids) {
postStr += "\"" + id + "\", ";
}
postStr += " ]}";
StringBuilder postString = new StringBuilder(postStr);
postString.replace(postStr.lastIndexOf(","),
postStr.lastIndexOf(",") + 1, "");
postStr = postString.toString();
// System.out.println("Reply id list : " + postStr);
Response response = client.target(URL + postURI)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Accept", "application/json")
.header("Authorization", "Basic " +
authStringEnc).header("Content-Type",
"application/json").post(Entity.json(postStr));
/*
* System.out.println("status: " + response.getStatus());
* System.out.println("headers \n: " + response.getHeaders());
* System.out.println("body: \n" +
response.readEntity(String.class));
*/
}
private void sendGet() throws Exception {
String url = URL + getURI;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
private void sendPost() throws Exception {
String url = URL + postURI;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
String urlParameters = "{\"reply_ids\":\"25ebbf01-5614-4ea6-a4f7-67b752d18ed2\",\"63ed8e18-ecf0-444d-b79e-341e944b0b94\"}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception {
/*
* System.setProperty("http.proxyHost", "");
* System.setProperty("http.proxyPort", "");
*/
APIcall apiCall = new APIcall();
apiCall.getRequest();
apiCall.postRequest();
}
}
If I understand correctly, they want you to convert this into a TestNG test which shouldn't be too difficult as the test and methods are already built. Considering you don't know Java, nor programming, I suggest watching a couple of Youtube videos to get you up to speed on TestNG. I believe once you get your feet wet with TestNG, much of the code along with how to convert it will make more sense.
#Test annotation will behave like a void main for each test (which is a method with the #Test annotation).
You can add a dependency in your maven pom.xml file for junit or testng (any of them will bring this annotation), then, you can trigger the test by running the method from your IDE, or from command line you can simple use:
mvn clean test - to trigger all existent tests
mvn clean test -Dtest=your.package.TestClassName - to trigger tests from a class
mvn clean test -Dtest=your.package.TestClassName#particularMethod - to trigger a specific test
I'm trying to access a Dynamics CRM Online REST API with Azure AD oAuth 2 Authentication. In order to do so I followed these steps:
I've registered a web application and/or web api in Azure
Configured the permissions to Dynamics CRM to have Delegated permissions "Access CRM Online as organization user"
And created a Key with a 1 year expiration and kept the Client ID generated.
My code:
package com.JasonLattimer.crm.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.naming.ServiceUnavailableException;
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
public class App {
// CRM URL
private final static String RESOURCE = "xxxxxx.crm8.dynamics.com";
private final static String CLIENT_ID = "xxxxxxx-xxxxx-xxxxxxx-xxxxxxxxx";
private final static String CLIENT_SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxx";
private final static String TENANTID = "xxxxxxxxxxx-xxxx-xxxxx-xxxxxxx";
private final static String AUTHORITY = "login.microsoftonline.com" + TENANTID + "/oauth2/authorize";
public static void main(String args[]) throws Exception {
AuthenticationResult result = getAccessTokenFromUserCredentials();
System.out.println("Access Token - " + result.getAccessToken());
System.out.println("Token expires on - " + result.getExpiresOn());
//String userId = WhoAmI(result.getAccessToken());
//System.out.println("UserId - " + userId);
String fullname = FindFullname(result.getAccessToken(), "2b8fc8ca-86cd-e611-8109-c4346bdc0e01");
System.out.println("Fullname: " + fullname);
}
private static AuthenticationResult getAccessTokenFromUserCredentials() throws Exception {
AuthenticationContext authContext = null;
AuthenticationResult authResult = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
authContext = new AuthenticationContext(AUTHORITY, false, service);
ClientCredential clientCred = new ClientCredential(CLIENT_ID, CLIENT_SECRET_KEY);
Future<AuthenticationResult> future = authContext.acquireToken(RESOURCE, clientCred, null);
authResult = future.get();
} catch (Exception ex) {
System.out.println(ex);
} finally {
service.shutdown();
}
if (authResult == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return authResult;
}
private static String FindFullname(String token, String userId) throws MalformedURLException, IOException {
System.out.println("AAAAAAAAAAAAAAAAAA");
HttpURLConnection connection = null;
//The URL will change in 2016 to include the API version - /api/data/v8.0/systemusers
URL url = new URL(RESOURCE + "/api/data/systemusers(" + userId + ")?$select=fullname");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Object jResponse;
jResponse = JSONValue.parse(response.toString());
JSONObject jObject = (JSONObject) jResponse;
String fullname = jObject.get("fullname").toString();
System.out.println("FULL NAME" + fullname);
return fullname;
}
private static String WhoAmI(String token) throws MalformedURLException, IOException {
HttpURLConnection connection = null;
//The URL will change in 2016 to include the API version - /api/data/v8.0/WhoAmI
URL url = new URL(RESOURCE + "/api/data/WhoAmI");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Object jResponse;
jResponse = JSONValue.parse(response.toString());
JSONObject jObject = (JSONObject) jResponse;
String userId = jObject.get("UserId").toString();
return userId;
}
}
I retrieve an access token successfully but when I try to do a httprequest to CRM I always get a 401 - Unauthorized status code. What am I missing?
You have 2 options:
The old way where you authenticate as a "normal" user in CRM (you'll need their password but can avoid a popup flow). C# example here.
The new way is "Server to Server authentication" which requires you to create an Application User. NOTE this example is also C# but the ADAL code should be very similar in Java.
I would like to generate POST request to a server which requires authentication. I tried to use the following method:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
but the server doesn't receive the authorization data. The line which is supposed to add authorization data is the following:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
and the line
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
also throws an IOException.
Anyway I would be very thankful if anyone could suggest any fix of the logic above in order to enable authorization using POST with UrlConnection.
but obviously it doesn't work as it is supposed to although if the same logic is used for GET request everything works fine.
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection to HttpURLConnection, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
I don't see anywhere in the code where you specify that this is a POST request. Then again, you need a java.net.HttpURLConnection to do that.
In fact, I highly recommend using HttpURLConnection instead of URLConnection, with conn.setRequestMethod("POST"); and see if it still gives you problems.
To do oAuth authentication to external app (INSTAGRAM) Step 3 "get the token after receiving the code" Only code below worked for me
Worth to state also that it worked for me using some localhost URL with a callback servlet configured with name "callback in web.xml and callback URL registered: e.g. localhost:8084/MyAPP/docs/insta/callback
BUT after successfully completed authentication steps, using same external site "INSTAGRAM" to do GET of Tags or MEDIA to retrieve JSON data using initial method didn't work.
Inside my servlet to do GET using url like
e.g. api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN only method found HERE worked
Thanks to all contributors
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> 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");
HttpsURLConnection conn = (HttpsURLConnection) 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);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
To send a POST request call:
connection.setDoOutput(true); // Triggers POST.
If you want to sent text in the request use:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(textToSend);
wr.flush();
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
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();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
#Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
#Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works.
My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());