Cannot access web page with credentials from java - java

I'm accessing RabbitMQ Queue information from java code.
public class NewClass {
private static Object Base64Converter;
public static void main(String args[])
{
try {
String credentials = "test" + ":" + "test";
String encoding = base64Encode(credentials);
URL url = new URL("http://192.168.0.30:15672/api/queues");
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
private static String base64Encode(String stringToEncode)
{
return DatatypeConverter.printBase64Binary(stringToEncode.getBytes());
}
java.io.IOException: Server returned HTTP response code: 401 for URL: http://192.168.0.30:15672/api/queues

You prepare a URLConnection with proper authentication but then you don't use it when you call url.openStream(). This should work:
...
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));

Related

Trouble with retriving data from a web service

I want to get data from an web service and after that to display it in a listView. So I made a function that get the data from the service, but when I tested it I discovered something unexpectedly. When I tested it as a call in the main function of the java class, it works, it returns me the data, but when I use it in the listView class, it doesn't. After some debugging, I still don't get why it doesn't work, but I observed that the only difference is that when the function is called in the main function, the URLConnection begins with sun.net.www.protocol.http.Http.URLConnection:http://... and when it's called in the listView class it begins with com.android.okhttp.internal.huc.HttpURLConnectionImpl:http//.. .
public static String getDataFromServer(String url) {
BufferedReader inputStream = null;
URL dataUrl = null;
String data = null;
//handle url exception
try {
dataUrl = new URL(url);
try {
URLConnection dc = dataUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
try {
inputStream = new BufferedReader(new InputStreamReader(dc.getInputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) { System.out.println(e.getMessage());}
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = inputStream.readLine())!=null)
sb.append(line + "\r\n");
data = sb.toString();
} catch (IOException e) { System.out.println(e.getMessage());
}
} catch (MalformedURLException e) { System.out.println(e.getMessage());}
return data;
}
do somthing like that :
String url = "http://youaddres.com/path";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//if it is post
con.setRequestMethod("POST");
String me = "{\"json\":\"" + json+ "\",\"json\":\"" + json+"\"}";
OutputStream os = con.getOutputStream();
os.write(me.getBytes());
os.flush();
InputStream inputStr = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStr));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String = response = sb.toString();

java get response from PayU api poland

I'm trying to integrate payu poland payment system to my website but cant get success response. Website done by jsp. Here is link that payu gave for help click im using "create a new order" for configuration. But its not retrieving any answer. Could anywane help me? Here is my jsp code:
`public static String sendPostRequest2(String requestUrl, String payload, String x, String y) {
StringBuilder jsonString = new StringBuilder();
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
writer.write(payload);
}
connection.setRequestProperty(x, y);
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
connection.disconnect();
} catch (IOException e) {
try {
URL url = new URL(requestUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
InputStream is;
if (httpConn.getResponseCode() >= 400) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
jsonString.append("<br>\n");
}
}
jsonString.append(new RuntimeException(e.getMessage()));
} catch (MalformedURLException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
jsonString.append(new RuntimeException(ex.getMessage()));
Logger.getLogger(PayU.class.getName()).log(Level.SEVERE, null, ex);
}
}
return jsonString.toString();
}
public static String get() {
String x = "";
String payload2 = "{ 'notifyUrl': 'https://your.eshop.com/notify', 'customerIp': '127.0.0.1', 'merchantPosId': '145227', 'description': 'RTV market', 'currencyCode': 'PLN', 'totalAmount': '21000', 'products': [ { 'name': 'Wireless mouse', 'unitPrice': '15000', 'quantity': '1' }, { 'name': 'HDMI cable', 'unitPrice': '6000', 'quantity': '1' } ]}";
String requestUrl2 = "https://secure.payu.com/api/v2_1/orders/";
x += sendPostRequest2(requestUrl2, payload2, "Authorization", "Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd");
return x;
}`
set the redirect turn off after that you will get the json response. So in your java code set redirect false.
connection.setInstanceFollowRedirects(false);

Error trying to post JSON data to Android Device

I've followed the tutorial here in an attempt to send data to an android device. I've whittled my Java class down to this:
public class App {
public static void main( String[] args ) {
try {
String apiKey = "api key generated in Google Developer Console...";
String deviceId = "Device Id generated, retrieved directly from logcat, as per tutorial...";
Content content = new Content();
content.addRegId(deviceId);
content.createData("Title", "Notification Message");
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
mapper.writeValue(wr, content);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println(responseCode == 200 ? responseCode + ". This is the response we want..." : responseCode + ". This is not the response we want...");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
and this is my Content class:
public class Content implements Serializable{
private List<String> registration_ids;
private Map<String,String> data;
public void addRegId(String regId) {
if(registration_ids == null)
registration_ids = new LinkedList<String>();
registration_ids.add(regId);
}
public void createData(String title, String message) {
if (data == null)
data = new HashMap<String,String>();
data.put("title", title);
data.put("message", message);
}
}
I'm getting a 400 response code
java.io.IOException: Server returned HTTP response code: 400 for URL: https://android.googleapis.com/gcm/send
I'm sure I'm missing something small, but I can't see where it is.

How to connect to MovieDB API webservice?

I am new to webservice and I am in the learning phase. Not much of the online content gives information about the use of MovieDB API webservice. Well for not I am just focusing on trying to get a movie information on the screen.
So the as per the API I am requesting the information and I am getting the JSON response when I paste http://api.themoviedb.org/3/movie/550?api_key=MYKEY in the browser.
I want to write a webservice using JAVA,SOAP to parse the JSON and fetch the required information. I tried using HttpURLConnection and then use BufferedReader but its not working.
Kindly suggest me some better options. Any links/blogs will be helpful.
This is the code snippet.
public class TestJSON {
/**
* #param args
*/
public static void main(String[] args) {
try{
URL url = new URL("http://api.themoviedb.org/3/movie/550?api_key=MYKEY/3/movie/550");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
String input = "";
OutputStream os = con.getOutputStream();
os.write(input.getBytes());
os.flush();
if (con.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
}
catch(MalformedURLException m){
System.out.println("Malformed URL");
}
catch(IOException ioe){
System.out.println("IO exception");
}
}
}
Thanks in advance.
Zingo
Try this code to read the output from the url:
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();

How to read an HTTP input stream?

The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}

Categories