I'm building webservice based on CXF and now I'm sending variables into some URL by code:
url = new URL(urlSSO + "/user");
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-EN");
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();
userInfo = response.toString();
if (userInfo != null) {
//do something
} else {
// some problem with user
return "home";
}
But I'm wondering if there is some more easy way to do this with CXF?
I mean, maybe CXF has something built-in?
I think that this code can take a lot of time to send and get response from other servlet... This CXF webservice will be put on servicemix, so I need something very fast to send variables
Related
We have a RabbitMQ Broker (V3.5.7) which is routing messages to a group of servers. When a server instance comes up (perhaps after a restart), I would like get a list of the current bindings for that server, so that I can confirm the bindings. The server is running Java, so that would be the preferred API.
It is an http call, something like that:
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL("http://localhost:15672/api/exchanges/%2F/topic_test/bindings/source");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
String userpass = "guest:guest";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setDoOutput(true);
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
maybe there are more efficient ways, but this is the idea
I would like to recover the values of my sim card to send it as a get or post to my app php I read several topic and I try a lot of things but I am novice in java. And I dont know how to send data taken from my java application to my web site.
String IMEINumber = manager.getDeviceId();
String SIMSerialNumber = manager.getSimSerialNumber();
BtnStart = (Button) findViewById(R.id.idBtnStart);
varText = (TextView) findViewById(R.id.idTxtView);
varText.setText(info);
I try this without succes:
URL url = new URL( "http://www.example.com/erm**?data=SIMSerialNumber**");
HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
Try using below code snippet: Code for Post request in java, sending request to specified URL.
HttpURLConnection connection = null;
JSONObject responseJsonObject = null;
try {
URL posturl = new URL("http://www.example.com/erm**?data=SIMSerialNumber**");
connection = (HttpURLConnection) posturl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "<type of your content>");
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
postBody -- will contain your value to be posted.
wr.write(postBody.toString().getBytes("UTF-8"));
wr.flush();
wr.close();
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();
Save your response in any format you want.I'm using Json format
responseJsonObject = new JSONObject(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
I want to send a POST request to this particular API: https://developer.lufthansa.com/docs/read/api_basics/Getting_Started and I researched how to do that and tried everything but it simply doesn't work, I always get an HTTP 400 or an HTTP 401 error. Here's my code:
private void setAccessToken(String clientID, String clientSecret) {
try {
URL url = new URL(URL_BASE + "oauth/token");
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(params);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
Kenta1561
Seems that your code is working well and it may be the case that you are providing invalid clientID or clientSecret so that your are getting wrong response in this case (as 401 indicates unauthorized). One thing you can do is you are only getting the response message if the http request status is ok (200). You may also get the invalid response message in case of 400 or 401 http response status. In order to print the invalid response messages you may follow the code below:
private void setAccessToken(String clientID, String clientSecret) throws Exception {
String params = "client_id=" + clientID + "&client_secret=" + clientSecret + "&grant_type=client_credentials";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
BufferedReader in;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
In this way you can also get invalid response message. In your case when I tried to hit the provided api it is giving me the response below:
{"error": "invalid_client"}
I want to write a Java application, which can login to a website For example, www.tumblr.com/login. Basically this web page asks for an email address on the first page and then would take the user to the next page to enter the password.
Can someone please help me with a sample Java code for this problem?
You might want to look at HttpURLConnection
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
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.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
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();
}
}
Code example found here
I keep keep getting the above error when I run the code below. All signs point to a problem with COOKIES from what I've read. If I am correct,how would I go about Implementing the CookieManager to fix this issue? Or how would I fix the issue if it is not an issue with COOKIES?
public class Client {
public Client(){
}
String executePost(String targetURL, String urlParameters){
URL url;
HttpURLConnection connection = null;
try{
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setChunkedStreamingMode(0);
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 dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(urlParameters);
dataout.flush();
dataout.close();
//get response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
response.append(line);
response.append('\n');
}
System.out.println(response.toString());
br.close();
return response.toString();
}catch(Exception e){
System.out.println("Unable to full create connection");
e.printStackTrace();
return null;
}finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
I removed : connection.setChunkedStreamingMode(0); and the code worked as it should
String executePost(String targetURL, String urlParameters){
URL url;
HttpURLConnection connection = null;
try{
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//send Request
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
dataout.writeBytes(urlParameters);
dataout.flush();
dataout.close();
//get response
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = br.readLine()) != null){
response.append(line);
response.append('\n');
}
System.out.println(response.toString());
br.close();
return response.toString();
}catch(Exception e){
System.out.println("Unable to full create connection");
e.printStackTrace();
return null;
}finally {
if(connection != null) {
connection.disconnect();
}
}
}
A 403 response means "forbidden".
All signs point to a problem with COOKIES from what I've read. If I am correct,how would I go about Implementing the CookieManager to fix this issue? Or how would I fix the issue if it is not an issue with COOKIES?
It is not as simple as that.
It may be that you need to supply valid credentials (in the form of cookies, basic auth headers, or something else). However, you expect the server to respond with a 401 in that case, or a 302 to redirect your browser the a login page.
It may also be that you've supplied credentials, and they are not sufficient for the request you are trying to perform.
Your best bet is to figure out exactly what is happening when you try to login and use the service from your web browser. Then try to replicate that. Alternatively, read the site documentation or ask the site admins what to do.
If it is your site / server that you are trying to access, then you need to figure out how security is implemented. Perhaps you've misconfigured the server, or neglected to set up / enable login.
It is unlikely (IMO) that you will solve this problem by just setting up a Cookie Manager.
If you see the API documentation of setChunkedStreamingMode, it has been mentioned there that not all servers support this mode. Are you sure that the server you are making a connection to supports this ?