how to use the perspective api, in java, I have tried several codes and it does not work too much .
I have do this, but not work.
`
try {
String url = "https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1&", key = "key=my_key";
final URL serverUrl = new URL(url + key);
URLConnection urlConnection = serverUrl.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)urlConnection;
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setDoOutput(true);
BufferedWriter httpRequestBodyWriter = new BufferedWriter(new
OutputStreamWriter(httpConnection.getOutputStream()));
httpRequestBodyWriter.write("{\"comment\": {\"text\": \"" + "Salut mec" + "\"},"
+ "\"requestedAttributes\": {\"TOXICITY\": {}}}");
httpRequestBodyWriter.flush();
httpRequestBodyWriter.close();
System.out.println("CODE : " + httpConnection.getResponseCode());
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
String output;
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}`
I have Code 404, and Caused by: java.io.FileNotFoundException: https://commentanalyzer.googleapis.com/$discovery/rest?version=v1alpha1&key=my_key
Have you an idea ?
Related
private void uploadDocToSharePoint(String token, Resource resource, String folderName) {
try {
String uploadUrl = Utils.SHARE_POINT_DOMAIN + "_api/web/getfolderbyserverrelativeurl('" + folderName + "')/files/add(url='" + resource.getFilename() + "', overwrite=true)";
URL url = new URL(uploadUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// Set Header
httpConn.setDoOutput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Authorization", "Bearer " + token);
httpConn.setRequestProperty("accept", "application/json; odata=verbose");
httpConn.setRequestProperty("Content-Type", "application/xml");
OutputStream os = httpConn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
httpConn.connect();
System.out.println(httpConn.getResponseCode());
System.out.println(httpConn.getResponseMessage());
String result;
BufferedInputStream bis = new BufferedInputStream(httpConn.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
buf.write((byte) result2);
result2 = bis.read();
}
result = buf.toString();
System.out.println(result);
} catch (Exception e) {
System.out.println("Error while reading file: " + e.getMessage());
}
}
httpConn.getResponseCode() is 400 and httpConn.getResponseMessage() is Bad Request.
I have tested this request with the URL generated in this class on Postman.
it works correctly.
so I am sure about url and token is correct.
It creates an Empty file successfully.
But as I mentioned the response status is 400 and Bad Request.
I am not sure what is wrong with the following class
Sharepoint guide here
My class copied from here
screenshot here
Pls follow Sharepoint guide here
I am trying to make a web proxy for HTTP communication between server and client. The GET method is working fine but I am POST method part is not working. I am sure I have missed out something. I want to know what have I missed or not implemented.
// request from client is handle from here
while ((inputLine = in.readLine()) != null) {
try {
StringTokenizer tok = new StringTokenizer(inputLine);
tok.nextToken();
} catch (Exception e) {
break;
}
if (cnt == 0) {
System.out.println("inputLine "+inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = tokens[1];
//hum inputline sy URL nikaal rahay hai
if(tokens[0]=="POST")
{
f=1;
}
System.out.println("Request for : " + urlToCall);
}
cnt++;
}
BufferedReader rd = null;
try {
//yaha sy hum ab server ko request send karay gy
URL url = new URL(urlToCall);
URLConnection conn = url.openConnection();
HttpURLConnection huc = (HttpURLConnection) conn;
conn.setDoInput(true);
conn.setDoOutput(false);
// now we will get the response from the server
if (f == 1) {
huc.setDoOutput(true);
huc.setInstanceFollowRedirects(false);
huc.setRequestMethod("POST");
huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty("charset", "utf-8");
}
InputStream is = null;
if (conn.getContentLength() > 0)
{
try {
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
} catch (IOException ioe) {
System.out.println(
"********* IO EXCEPTION **********: " + ioe);
}
}
What is the error you are getting on the post? And what is a sample GET request that is being passed into your code?
When I use a simple GET request, the code fails because the urlToCall does not have the host or protocol. The below code worked for me, but I would highly suggest you change your code to not hide the exceptions that are being thrown because they will have important information about what is going wrong with your code.
if (cnt == 1) {
System.out.println("host: " + inputLine);
String[] tokens = inputLine.split(" ");
urlToCall = "HTTP://" + tokens[1] + urlToCall;
}
I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...
I'm trying to set the OAuth Authorization header of a HttpsURLConnection object and below is the java code for that
String url1 = "/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String header = OAuthClient.prepareURLWithOAuthSignature(url1);
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "OAuth " + header);
System.out.println("Request properties = " + con.getRequestProperty("Authorization"));
int responseCode = con.getResponseCode();
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();
con.disconnect();
//print result
System.out.println("Response = " + response.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null) con.disconnect();
}
And below is the code for prepareURLWithOAuthSignature
public String prepareURLWithOAuthSignature(String url)
{
String signature = null;
setOAuthParameters();
setOAuthQParams();
try
{
httpURL = URLEncoder.encode(baseURL+url, "UTF-8");
signature = OAuthSignatureService.getSignature(httpURL, URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"), consumer_secret);
OAuthParameters.put("oauth_signature", signature);
} catch (Exception e) {
e.printStackTrace();
}
return getOAuthAuthorizationHeader();
}
public String getOAuthAuthorizationHeader()
{
String OAuthHeader = "oauth_consumer_key=\"" + OAuthParameters.get("oauth_consumer_key") + "\"" +
",oauth_signature_method=\"" + OAuthParameters.get("oauth_signature_method") + "\"" +
",oauth_timestamp=\"" + OAuthParameters.get("oauth_timestamp") + "\"" +
",oauth_nonce=\"" + OAuthParameters.get("oauth_nonce") + "\"" +
",oauth_version=\"" + OAuthParameters.get("oauth_version") + "\"" +
",oauth_signature=\"" + OAuthParameters.get("oauth_signature") + "\"";
byte[] authEncBytes = Base64.encodeBase64(OAuthHeader.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
The problem is that
1) while I'm printing the con.getRequestProperty("Authorization") I'm getting a null value which means the Authorization header is not set
2) The final response I'm getting from the server is 403
Any idea what's going wrong here?
I know this might not be an answer but looks like this issue was submitted as a bug to sun and here is the relevant part of the reply.
This behavior is intentional in order to prevent a security hole that
getRequestProperty() opened. setRequestProperty("Authorization")
should still work, you just won't be able to proof the results via
getRequestProperty().
For the original forum post, please see: http://www.coderanch.com/t/205485/sockets/java/setRequestProperty-authorization-JDK
I would not be able to advice why you're getting a 403 but try adding the "Content-Type" request header to your connection and see if it makes any difference. Until I added that header in my code, I was getting a 404 back from the Spring Security module.
I have a java servlet class that is performing a GET to a specific URL. I am also passing data as part of the GET.
What I need, is in my HTTP Server code that recieves this data, how do I insert user based response data into the Header back so my calling Java servlet class can read it.
I can read standard response things like .getResponseCode() etc, but I need to insert my own response into the header some how. How can this be done? and how can I read it?
This is my java servlet send class:
public void sendRequest(String data, String sendUrl) throws Throwable{
String messageEncoded = URLEncoder.encode(data, "UTF-8");
String message = URLDecoder.decode(messageEncoded);
System.out.println("messageEncoded : " + messageEncoded);
System.out.println("messageDecoded : " + message);
try {
URL url = new URL(sendUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(message);
writer.close();
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : connection.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Ok
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
System.out.println(this.getClass() + " : MalformedURLException Error occured due to: " + e);
} catch (IOException e) {
System.out.println(this.getClass() + " : IOException Error occured due to: " + e);
}
}