can't solve java.net.MalformedURLException - java

public class AnalyticsDetectLanguage {
static String subscription_key_var;
static String subscription_key;
static String endpoint_var;
static String endpoint;
public static void Initialize () throws Exception {
subscription_key = "xxxxxx";
endpoint = "xxxxxxx";
}
static String path = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages";
public static String GetLanguage (Documents documents) throws Exception {
String text = new Gson().toJson(documents);
byte[] encoded_text = text.getBytes("UTF-8");
URL url = new URL(endpoint+path);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/json");
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscription_key);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(encoded_text, 0, encoded_text.length);
wr.flush();
wr.close();
StringBuilder response = new StringBuilder ();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
public static String prettify(String json_text) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(json_text).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(json);
}
public static void main (String[] args) {
try {
Initialize();
Documents documents = new Documents ();
documents.add ("1", "This is a document written in English.");
documents.add ("2", "Este es un document escrito en Español.");
documents.add ("3", "这是一个用中文写的文件");
String response = GetLanguage (documents);
System.out.println (prettify (response));
}
catch (Exception e) {
System.out.println (e);
}
}
}
I am trying to work with the microsoft azure text analytics API but when I run this code with the correct keys I get a java.net.MalformedURLException on the endpoint key which itself is correct, but the error returns the key as xxxxxxxhttps. How do I get the code to run?

endpoint = "xxxxxxx";
URL url = new URL(endpoint+path);
The URL you end up with is "xxxxxxxhttps://northeurope.api.cognitive.microsoft.com/text/analytics/v2.1/languages".
Which is not a valid URL.

Related

How to fetch token from Token API using Java

I am trying to fetch token by calling token API but unable to fetch the same.
It is working in postman.
Postman details are as follows
My code
import java.io.*;
import java.net.*;
public class GetToken {
public static void main(String[] args) {
// TODO Auto-generated method stub
String accessToken = "";
String tokenURL="https://test.iapsoftware.com/iap6/MobileServices/token";
String grantType = "password";
String userName="APITester";
String password="password";
String ClientCode ="iaptest1";
String ClientInterface ="API";
try {
URL url = new URL(tokenURL);
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
// Set header
httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("ClientCode", ClientCode);
httpConn.setRequestProperty("ClientInterface", ClientInterface);
//httpConn.setRequestBody();
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
//Set Request Body
String jsonInputString =("grant_type="+grantType+",username="+userName+",password="+password);
OutputStream os = httpConn.getOutputStream();
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
// Read the response.
InputStreamReader isr=null;
if (httpConn.getResponseCode() == 200) {
isr = new InputStreamReader(httpConn.getInputStream());
}
else
{
isr = new InputStreamReader(httpConn.getErrorStream());
}
BufferedReader in = new BufferedReader(isr);
String responseString = "";
String outputString = "";
// Write response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
accessToken = outputString;
}
catch (Exception e)
{
accessToken = "Error"; //+ e.getMessage();
}
System.out.println(accessToken);
}
}
error
-As per my understanding I am not passing correct input.
Input needs to be URL encoded and I am sending it as JSON.
Kindly suggest and provide solution for the same.
After setting up the body correctly it worked
String urlParameters = ("grant_type="+grantType+"&username="+userName+"&password="+password);
OutputStream os = httpConn.getOutputStream();
byte[] postData = urlParameters.getBytes("utf-8");
int postDataLength = postData.length;
os.write(postData, 0, postDataLength);

Unable to unzip the web service response in Linux using java

We are executing web services using java code. The web service response comes in gzip format from the web service provider. We are unzipping the response using GZIPInputStream after receiving the response.
Response is converted into byte codes and then passing as input to gzipinputstream. This code is working fine in Eclipse and able to unzip the response string. The same code is not working in Linux and throwing the error "Not in Gzip format" while passing the byte array to gzipinputstream.
We checked the default charset in Windows is windows-1252 and in Linux is UTF-8. So, we tried to get the bytes in UTF-8 and windows-1252. Both are not working.
Can anyone please help me where is it going wrong and how to resolve the issue?
Tried changing the charset while generating the byte codes of the response.
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.io. * ;
import java.nio.charset.*;
import java.util.zip.GZIPInputStream;
import java.nio.charset.*;
public class WSConnectTest {
public final static String UserName = null; //User id login for Fusion
public final static String instanceURL = null;
public final static String USER_PWD = null; // API key shared by CSOD
private static final String PROXY_URL = null; //UBS proxy URL
private static final int PROXY_PORT = 8080;
private static final String PROXY_USERNAME = "USER_NAME";
private static final String PROXY_PASSWORD = "PASSWORD";
final static String USER_AGENT = "Mozilla/5.0";
static Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
PROXY_URL, PROXY_PORT));
static {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(UserName, USER_PWD.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
public static void main(String[] args) throws Exception {
FusionConnect fusionconnect = new FusionConnect();
String theURL = instanceURL + "<RESOURCE_NAME>";
System.out.println("The URL to be called is : " + theURL);
String json = "<JSON_STRING>"
String post_param = new String(json.toString());
System.out.println("The json is :" + json);
PostRequestWithFilter(theURL, post_param);
}
private static void PostRequestWithFilter(String url, String json) throws Exception {
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection(proxy);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept-Language", "UTF-8");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setDoOutput(true);
con.setConnectTimeout(15000);
System.out.println("get content type :"+con.getRequestProperties());
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("\nResponse Code : " + responseCode);
System.out.println("\nResponse message : " + con.getResponseMessage());
String inputLine;
StringBuffer response = new StringBuffer();
String ResponseStr = null;
byte[] bresponse = new byte[1024];
String deoutput = null;
BufferedReader in =null;
if (responseCode == con.HTTP_CREATED) { in =new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
System.out.println("Response received from Fusion string buffer :"+inputLine);
} in .close();
ResponseStr = response.toString();
System.out.println("response string :"+ResponseStr);
bresponse = ResponseStr.getBytes("UTF-8");
System.out.println("Response received from Fusion Bytes :"+bresponse);
deoutput = unzip(bresponse);
System.out.println("Decompressed response :"+deoutput);
} else { in =new BufferedReader(new InputStreamReader(con.getErrorStream()));
System.out.println("Response Content Type :"+con.getContentType());
System.out.println("Response Content Encoding :"+con.getContentEncoding());
while ((inputLine = in.readLine()) != null) {
response.append(inputLine+"\r");
System.out.println("Response received from Fusion string buffer :"+inputLine);
}
in .close();
ResponseStr = response.toString();
System.out.println("response string :"+response);
bresponse = ResponseStr.getBytes();
for (int i=0; i < bresponse.length; i++)
{
System.out.println("byte code :"+i+" "+bresponse[i]);
}
System.out.println("Response received from Fusion Bytes :"+Charset.defaultCharset()+bresponse);
deoutput = unzip(bresponse);
FileOutputStream fos = new FileOutputStream("fileName1.gz");
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(ResponseStr);
outStream.close();
System.out.println("Decompressed response :"+deoutput);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public static String unzip(byte[] compressed) {
if ((compressed == null) || (compressed.length == 0)) {
System.out.println("The response is empty");
throw new IllegalArgumentException("Cannot unzip null or empty bytes");
}
if (!isZipped(compressed)) {
System.out.println("The response is not zipped");
return new String(compressed);
}
StringBuilder output = new StringBuilder();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
System.out.println("After byte array input stream :");
try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
try (InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream, StandardCharsets.UTF_8)){
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
System.out.println("buffer reader :"+bufferedReader.readLine());
while ((line = bufferedReader.readLine()) != null) {
output.append(line);
System.out.println("line :"+output.toString());
}
} catch(IOException e) {
throw new RuntimeException("Failed to read bufferedReader content", e);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static boolean isZipped(final byte[] compressed) {
System.out.println("(byte)(GZIPInputStream.GZIP_MAGIC) is "+(byte)(GZIPInputStream.GZIP_MAGIC));
System.out.println("gzip magic is "+(byte)(GZIPInputStream.GZIP_MAGIC >> 8));
return (compressed[0] == (byte)(GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte)(GZIPInputStream.GZIP_MAGIC >> 8));
}
}

How to get json response data using facebook graph api 2.5?

I have a code that brings the json response from the twitter api. I want to use same code for facebook graph api to get json response from the Facebook but facebook doesn't provide any consumer keys as twitter. I can change this code to get the facebook json response. Can any of you help to modify the code.
public class TwitterResponse {
static String AccessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String AccessSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
static String ConsumerSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
/**
* #param args
*/
public static void main(String[] args) throws Exception
{
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(ConsumerKey,ConsumerSecret);
String twitterUrl="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=heymailme143&count=1&include_rts=true&contributors=true";
consumer.setTokenWithSecret(AccessToken, AccessSecret);
//HttpGet request = new HttpGet("https://api.twitter.com/1.1/friends/list.json");
HttpGet request = new HttpGet(twitter);
consumer.sign(request);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String m=IOUtils.toString(response.getEntity().getContent());
System.out.println(m);
System.out.println(statusCode + ":" + response.getStatusLine().getReasonPhrase());
}
}
This is a sample code I used to get the twitter response. Could you help me in changing it to get the facebook response using fb graph api?
Have a look at
http://facebook4j.org/en/index.html
which also has some examples.
I'm Looking for this :)
public String getUserInfo(String access_token) throws MalformedURLException, ProtocolException, IOException {
try {
String connection = connectionGet("https://graph.facebook.com/me?access_token=" + access_token, "");
System.out.println("done");
return connection;
} catch (Exception e) {
System.out.println("null value");
return null;
}
}
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
System.out.println(sb.toString());
return sb.toString();
}}

Cannot access web page with credentials from 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()));

Reading from a URL Connection Java

I'm trying to read html code from a URL Connection. In one case the html file I'm trying to read includes 5 line breaks before the actual doc type declaration. In this case the input reader throws an exception for EOF.
URL pageUrl =
new URL(
"http://www.nytimes.com/2011/03/15/sports/basketball/15nbaround.html"
);
URLConnection getConn = pageUrl.openConnection();
getConn.connect();
DataInputStream dis = new DataInputStream(getConn.getInputStream());
//some read method here
Has anyone ran into a problem like this?
URL pageUrl = new URL("http://www.nytimes.com/2011/03/15/sports/basketball/15nbaround.html");
URLConnection getConn = pageUrl.openConnection();
getConn.connect();
DataInputStream dis = new DataInputStream(getConn.getInputStream());
String urlData = "";
while ((urlData = dis.readUTF()) != null)
System.out.println(urlData);
//exception thrown
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
at java.io.DataInputStream.readUTF(DataInputStream.java:572)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
in the case of bufferedreader, it just responds null and doesn't continue
pageUrl = new URL("http://www.nytimes.com/2011/03/15/sports/basketball/15nbaround.html");
URLConnection getConn = pageUrl.openConnection();
getConn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(getConn.getInputStream()));
String urlData = "";
while(true)
urlData = br.readLine();
System.out.println(urlData);
outputs null
You're using DataInputStream to read data that wasn't encoded using DataOutputStream. Examine the documented behavior for your call to DataInputStream#readUtf(); it first reads two bytes to form a 16-bit integer, indicating the number of bytes that follow comprising the UTF-encoded string. The data you're reading from the HTTP server is not encoded in this format.
Instead, the HTTP server is sending headers encoded in ASCII, per RFC 2616 sections 6.1 and 2.2. You need to read the headers as text, and then determine how the message body (the "entity") is encoded.
This works fine:
package url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
/**
* UrlReader
* #author Michael
* #since 3/20/11
*/
public class UrlReader
{
public static void main(String[] args)
{
UrlReader urlReader = new UrlReader();
for (String url : args)
{
try
{
String contents = urlReader.readContents(url);
System.out.printf("url: %s contents: %s\n", url, contents);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public String readContents(String address) throws IOException
{
StringBuilder contents = new StringBuilder(2048);
BufferedReader br = null;
try
{
URL url = new URL(address);
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
while (line != null)
{
line = br.readLine();
contents.append(line);
}
}
finally
{
close(br);
}
return contents.toString();
}
private static void close(Reader br)
{
try
{
if (br != null)
{
br.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This:
public class Main {
public static void main(String[] args)
throws MalformedURLException, IOException
{
URL pageUrl = new URL("http://www.google.com");
URLConnection getConn = pageUrl.openConnection();
getConn.connect();
BufferedReader dis = new BufferedReader(
new InputStreamReader(
getConn.getInputStream()));
String myString;
while ((myString = dis.readLine()) != null)
{
System.out.println(myString);
}
}
}
Works perfectly. The URL you are supplying, however, returns nothing.

Categories