Does anyone know if there is a Google Reader service call that a user can make to get the name/uri of all feeds that fall under a certain label/category? Thanks!
You can use a variation of the code below to get access to the Google Reader system. You need to send the header ("Authorization", "auth=" +myauthvar) with each request. In order to edit items you will need the token which I also demo below. Once you have the auth id you can post (with that header intact) to http://www.google.com/reader/api/0/subscription/list?output=xml in order to return the full subscription listing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
getAuth();
Console.ReadLine();
}
public static void getAuth()
{
//put in the username and password
string postData = "Email=YOURUSERNAME#gmail.com&Passwd=YOURPASSWORD&service=reader&source=some-uniqueapp-v1";
WebRequest authReq = WebRequest.Create("https://www.google.com/accounts/ClientLogin");
authReq.ContentType = "application/x-www-form-urlencoded";
authReq.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(postData);
authReq.ContentLength = bytes.Length;
Stream os = authReq.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
WebResponse resp = authReq.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string responseContent = sr.ReadToEnd().Trim();
string[] responseSpilt = responseContent.Split('=');
string authticket = responseSpilt[3];
Console.WriteLine("Auth = " + authticket);
sr.Close();
getToken(authticket);
}
public static void getToken(string auth)
{
WebRequest tokenReq = WebRequest.Create("https://www.google.com/reader/api/0/token");
tokenReq.ContentType = "application/x-www-form-urlendcoded";
tokenReq.Method = "GET";
tokenReq.Headers.Add("Authorization", "GoogleLogin auth=" + auth);
WebResponse response = tokenReq.GetResponse();
if (response == null) return;
StreamReader sr = new StreamReader(response.GetResponseStream());
string respContent = sr.ReadToEnd().Trim();
string[] respSplit = respContent.Split('/');
string token = respSplit[2];
Console.WriteLine(" ");
Console.WriteLine("Token = " + token);
sr.Close();
}
}
}
Related
I have an example working solution in Java but I need a solution in C# that can be called from a legacy database system.
So basically create a request with custom headers, load a Word document, and send the request. The server will then convert the Word document and return the PDF which then needs to be saved to disk.
Can someone please assist.
Java Code
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class NewMain {
public static void main(String[] args) throws IOException {
String source = args[0];
String target = args[1];
URL url = new URL("http://localhost:9998");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/vnd.com.documents4j.any-msword");
conn.setRequestProperty("Accept", "application/pdf");
conn.setRequestProperty("Converter-Job-Priority", "1000");
// File wordFile = new File("C:/temp2/Sample.doc");
File wordFile = new File(source);
InputStream targetStream = new FileInputStream(wordFile);
OutputStream os = conn.getOutputStream();
long length = targetStream.transferTo(os);
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
InputStream in = conn.getInputStream();
// OutputStream out = new FileOutputStream("C:/temp2/Sample-BBB-doc.pdf");
OutputStream out = new FileOutputStream(target);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
os.close();
conn.disconnect();
}
}
The following is C# code that I have been progressing with [Note not attempt to save the returned PDF as yet] - below this is the server response:
using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace HttpPOST10
{
class Program
{
public static string MyUri { get; private set; }
static void Main(string[] args)
{
string url = "http://localhost:9998";
Uri myUri = new Uri(url);
string filePath = #"C:\temp2";
string srcFilename = #"C:\temp2\Sample.doc";
string destFileName = #"C:\temp3\Sample.pdf";
UploadFile(url, filePath, srcFilename, destFileName);
}
private static bool UploadFile(string url, string filePath, string srcFilename, string destFileName)
{
HttpClient httpClient = new HttpClient();
using var fileStream = new FileStream(srcFilename, FileMode.Open);
var fileInfo = new FileInfo(srcFilename);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers = {
{ HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
{ HttpRequestHeader.Accept.ToString(), "application/pdf" },
{"Converter-Job-Priority", "1000"}
},
Content = new StreamContent(fileStream)
};
Console.Write("httpRequestMessage:" + httpRequestMessage);
var response = httpClient.SendAsync(httpRequestMessage).Result;
Console.Write("response:" + response);
return true;
}
}
}
Http Response:
httpRequestMessage:Method: POST, RequestUri: 'http://localhost:9998/', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
ContentType: application/vnd.com.documents4j.any-msword
Accept: application/pdf
Converter-Job-Priority: 1000
}response:StatusCode: 500, ReasonPhrase: 'Request failed.', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: close
Content-Length: 1031
Content-Type: text/html; charset=ISO-8859-1
Alternative Solution restSharp
I have made some progress today and managed to create a basic working solution in restSharp. This was derived from investigating how things work in Postman and starting with the generated code snippet. The challenge was getting the source document recognized so it could be uploaded (seems like a bit of confusion as to what each of the file parameters are used for):
using System;
using System.IO;
using System.Net;
using RestSharp;
using RestSharp.Extensions;
namespace HttpPOST12RestSharp
{
class Program
{
static void Main(string[] args)
{
var source = "C:\\temp2\\Sample.doc";
var target = #"C:\temp3\Sample-HttpPOST12RestSharp.pdf";
var client = new RestClient("http://localhost:9998");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/vnd.com.documents4j.any-msword");
request.AddHeader("Accept", "application/pdf");
request.AddHeader("Converter-Job-Priority", " 1000");
request.AddParameter("application/vnd.com.documents4j.any-msword", File.ReadAllBytes(source), Path.GetFileName(source), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine("response.StatusCode: " + response.StatusCode);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"Unable to download file");
}
else
{
response.RawBytes.SaveAs(target);
Console.WriteLine("Target Document: " + target);
}
}
}
}
Alternative Solution HttpClient / HttpRequestMessage
This solution uses HttpClient / HttpRequestMessage with no external libraries and saves the returned PDF response to disk.
using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
namespace HttpPOST10
{
class Program
{
public static string MyUri { get; private set; }
static void Main(string[] args)
{
string url = "http://localhost:9998";
// string url = "http://localhost:8888"; // Fiddler
Uri myUri = new Uri(url);
string srcFilename = #"C:\temp2\Sample.doc";
string destFileName = #"C:\temp3\Sample-HttpPOST10.pdf";
UploadFileAsync(url, srcFilename, destFileName);
}
private static async System.Threading.Tasks.Task<bool> UploadFileAsync(string url, string srcFilename, string destFileName)
{
HttpClient httpClient = new HttpClient();
byte[] data;
data = File.ReadAllBytes(srcFilename);
HttpContent content = new ByteArrayContent(data);
content.Headers.Add("Content-Type", "application/vnd.com.documents4j.any-msword");
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers = {
// { HttpRequestHeader.ContentType.ToString(), "application/vnd.com.documents4j.any-msword" },
{ HttpRequestHeader.Accept.ToString(), "application/pdf" },
{ "Converter-Job-Priority", "1000" },
},
Content = content
};
Console.Write("httpRequestMessage:" + httpRequestMessage);
var response = httpClient.SendAsync(httpRequestMessage).Result;
Console.Write("response:" + response);
using (var fs = new FileStream(destFileName, FileMode.CreateNew))
{
await response.Content.CopyToAsync(fs);
}
return true;
}
}
}
Request / Response
httpRequestMessage:Method: POST, RequestUri: 'http://localhost:9998/',
Version: 1.1, Content: System.Net.Http.ByteArrayContent, Headers: {
Accept: application/pdf Converter-Job-Priority: 1000 Content-Type:
application/vnd.com.documents4j.any-msword }response:StatusCode: 200,
ReasonPhrase: 'OK', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding
Transfer-Encoding: chunked Date: Mon, 12 Apr 2021 06:49:45 GMT
Content-Type: application/pdf
I am able to create SOAP Project and execute associated test case.
SOAP Code Snippet:
public String executeSoapTestcase(final SoapUIData soapUIData) throws Exception {
SoapUI.getSettings().setBoolean(HttpSettings.RESPONSE_COMPRESSION, false);
final WsdlProject project = new WsdlProject();
String response = null;
final WsdlInterface[] ifaceArray = WsdlInterfaceFactory.importWsdl(project, soapUIData.getWsdlPath(), true);
if (ifaceArray == null) {
throw new IllegalArgumentException(
"inside SoapUIService.executeTestcase Binding not found in the specified WSDL");
}
final WsdlInterface wsdlInterface = ifaceArray[0];
Operation[] wsdlOperations = wsdlInterface.getAllOperations();
if (wsdlOperations == null) {
throw new IllegalArgumentException(
"inside SoapUIService.executeTestcase Operations not found in the specified WSDL");
}
wsdlInterface.changeEndpoint(wsdlInterface.getEndpoints()[0], soapUIData.getEndpoint());
final WsdlOperation operation = (WsdlOperation) wsdlOperations[0];
final WsdlRequest request = operation.addNewRequest("addRequest");
request.setRequestContent(soapUIData.getXmlRequest());
final WsdlSubmit<?> wsdlSubmit = (WsdlSubmit<?>) request.submit(new WsdlSubmitContext(request), false);
final WsdlResponse wsdlResponse = (WsdlResponse) wsdlSubmit.getResponse();
log.info("inside utm-soapui-service SoapUIService.executeTestcase Submit status : " + wsdlSubmit.getStatus());
if (wsdlResponse != null) {
response = wsdlResponse.getContentAsString();
}
return response;
}
Same thing i want to do for REST Project: I want to create Rest Project using wadl and execute test case.
public void executeRestTestcase() throws Exception {
final WsdlProject project = new WsdlProject();
final RestServiceBuilder serviceBuilder = new RestServiceBuilder();
serviceBuilder.createRestService(project,"Your Rest URL");
final StringToStringMap headers = new StringToStringMap();
headers.put("Authorization", "Basic **********");
headers.put("Accept", "application/json");
final RestRequest request =
(RestRequest) project.getInterfaceList().get(0).getOperationList().get(0).getRequestList().get(0);
request.setRequestHeaders(headers);
final Submit submit = (Submit) request.submit(new WsdlSubmitContext(request), false);
final Response response = submit.getResponse();
String responseContent = response.getContentAsString();
log.info(responseContent);
}
The above solution is working fine but by default it is using GET and could not able to find any method to change from GET to POST.
I am trying to send POST request with REST Body and looking for the code for the same
public void executeRestTestcase() throws Exception {
final WsdlProject project = new WsdlProject();
final RestServiceBuilder serviceBuilder = new RestServiceBuilder();
serviceBuilder.createRestService(project,"http://restapi.adequateshop.com/api/authaccount/registration");
final StringToStringMap headers = new StringToStringMap();
headers.put("Authorization", "Basic a93e4973-11f8-4efe-9d22-6edc3d46c186");
headers.put("Accept", "application/json");
final RestRequest request = (RestRequest) project.getInterfaceList().get(0).getOperationList().get(0).getRequestList().get(0);
request.setRequestHeaders(headers);
ReadJsonAsString redjson = new ReadJsonAsString();
String testrf = redjson.readFileAsString("");
request.setRequestContent(testrf);
RestMethod HttpMethod = request.getRestMethod();
WsdlSubmit submit = (WsdlSubmit) request.submit(new WsdlSubmitContext(request), false);
final Response response = submit.getResponse();
String responseContent = response.getContentAsString();
System.out.println("RESPONSE: " + responseContent);
}
I have a Java web app that posts items to our users facebook walls, when the user initially signs up we get a 60 day access_token which is persisted to our database, now that the offline_access is be removed I using our 'Login with facebook' button to update the tokens when the user logs into our website, this is all good as they will typically visit more than 60 days apart.
I have implemented the above and it works well...but then I found that the access tokens that are being generated from the login action expire after 1 hour....obviously not good a we cant post to their walls while they are away.
The code below demonstrates how we are getting the tokens via the signed_request method (in Java SEAM App), this works ok, but the tokens are short-lived
Can anyone suggest how to ensure the tokens are the 60-day type
Thanks
public void loginWithFacebook(){
accessToken = null;
try {
accessToken = FaceBookSecurity.getFBAccessToken();
} catch (Exception e) {
log.error("Error getting FB access token: "+e);
}
FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
com.restfb.types.User facebookUser = facebookClient.fetchObject("me", com.restfb.types.User.class);
facebookEmail = facebookUser.getEmail();
if (facebookEmail != null) {
new RunAsOperation(true) {
public void execute() {
user = ((UserDAO)Component.getInstance("userDAO")).findByEmail(StringUtils.lowerCase(facebookEmail));
if (user != null && user.getFacebookToken() != null && !accessToken.equals(user.getFacebookToken())) {
user.setFacebookToken(accessToken);
log.error("FB: updating "+user.getFirstname()+" "+user.getSurname()+"s FB token to: "+accessToken);
}
}
}.run();
if (user != null) {
//set the user as logged in
return;
}
}
messagePoster.postPopupErrorMessage(messages.get("facebookLoginFailed"));
}
public static String getFBAccessToken()
throws Exception {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Cookie fbCookie = getFBCookie(request);
String fbCookieValue = fbCookie.getValue();
String[] stringArgs = fbCookieValue.split("\\.");
String encodedPayload = stringArgs[1];
JsonObject data;
try{
String payload = base64UrlDecode(encodedPayload);
// gets the js object from the cookie
data = new JsonObject(payload);
}catch (Exception e){
return "";
}
String authUrl = getAuthURL(data.getString("code"));
URL url = new URL(authUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
String result = readURL(uri.toURL());
String[] resultSplited = result.split("&");
return resultSplited[0].split("=")[1];
}
// creates the url for calling to oauth.
public static String getAuthURL(String authCode) {
String url = "https://graph.facebook.com/oauth/access_token?client_id="
+ FacebookApp.appId
+ "&redirect_uri=&client_secret="
+ FacebookApp.appSecret + "&code="
+ authCode;
return url;
}
// reads the url.
private static String readURL(URL url) throws IOException {
InputStream is = url.openStream();
InputStreamReader inStreamReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(inStreamReader);
String s = "";
int r;
while ((r = is.read()) != -1) {
s = reader.readLine();
}
reader.close();
return s;
}
private static String base64UrlDecode(String input){
return new String(Base64.decodeBase64(input.getBytes()));
}
If all you need is to post to the user's wall, then you can also use app_access_token provided you have asked for publish_stream permission.
You can call :
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID
&client_secret=YOUR_APP_SECRET
&grant_type=client_credentials
Read this.
Edit: app access_tokens do not expire until the app secret is reset.
I can't figure this one out. I'm trying to dynamically roll keys. I can create the POST request fine, but receive a 400 error and a stacktrace with an IOException when I call post. Below is a self-contained example. I'm using JSCH to generate keys. API doc: http://developer.github.com/v3/users/keys/
The API call: POST /user/keys
public static class LiberalHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String post(String requestUrl, Map<String, String> params,
String username, String password) throws Exception {
String data = "";
int paramCount = 1;
for (Entry<String, String> param : params.entrySet()) {
if (paramCount == 1) {
data = URLEncoder.encode(param.getKey(), "UTF-8") + "="
+ URLEncoder.encode(param.getValue(), "UTF-8");
} else {
data += "&" + URLEncoder.encode(param.getKey(), "UTF-8") + "="
+ URLEncoder.encode(param.getValue(), "UTF-8");
}
paramCount++;
}
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) (url).openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setHostnameVerifier(new LiberalHostnameVerifier());
BASE64Encoder enc = new BASE64Encoder();
String userAuth = username + ":" + password;
String encodedAuthorization = enc.encode(userAuth.getBytes());
conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
String response = "";
while ((line = rd.readLine()) != null) {
response += line;
}
wr.close();
rd.close();
return response;
}
public static KeyPair generateKey(String filename) throws Exception {
JSch jsch = new JSch();
try {
KeyPair kpair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
kpair.setPassphrase("");
kpair.writePrivateKey(filename + ".pem");
kpair.writePublicKey(filename + ".pub", "Auto-generated.");
System.out.println("Finger print: " + kpair.getFingerPrint());
// kpair.dispose();
return kpair;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getFileContents(File file) throws Exception {
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
f.read(buffer);
return new String(buffer);
}
public static String createKey(String title) throws Exception {
generateKey(title);
final String key = getFileContents(new File(
"/Users/franklovecchio/Desktop/development/" + title
+ ".pub"));
System.out.println("key: " + key);
Map<String, String> params = new HashMap<String, String>() {
{
put("title", title);
put("key", key);
}
};
return post("https://api.github.com/user/keys", params, "username",
"password");
}
// call createKey("key);
Thanks to #nico_ekito and #J-16 SDiZ for helping in the right direction. If you look closely at the documentation, the request doesn't use standard POST parameters, but rather takes JSON as Raw Input, and the ssh-rsa key can NOT be encoded. Next up, I can't get GSON to not encode a string, even using disableHtmlEscaping. So, I had to fake it:
String json = "{\"title\":\"" + title + "\",\"key\":\"" + key.trim() + "\"}";
Did you try a ssh library (e.g. JSch). They can generate RSA key in SSH consumable format.
I am looking for some alternatives of consuming a SOAP web service in java. I am currently using a stub method to consume it and it's too simple for my instructor needs. My instructor said to do a trivial client, what was that suppose to mean?
SOAP is basically the submission of XML to a web server using the POST method. While the XML can get verbose, you should be able to construct the XML using StringBuilder and then use a simple HTTP client, like the Apache HttpClient to construct a POST request to a URL using
the XML string as the body.
That's about as simple as they come.
Here is the simple and lightweight example for consuming the soap api. Steps are below.
You must create the SOAPTestController.java, KflConstants.java And SoapClient.java class.
Then Implement the below code blocks and enjoy it.
Here is the SOAPTestController.java class
#Controller
public class SOAPTestController {
#RequestMapping(value = "/showdate", method = RequestMethod.GET)
public #ResponseBody String getDateAndTime() {
String DateAndTimeSOAPRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n"
+ " <soap12:Body>\r\n" + " <GetDateAndTime xmlns=\"http://tempuri.org/\" />\r\n"
+ " </soap12:Body>\r\n" + "</soap12:Envelope>";
String Fundtion = "GetDateAndTime";
return new SoapClient().ConsumeTheService(DateAndTimeSOAPRequest, "GetDateAndTime");
}
}
This is the KflConstants.java class
public class KflConstants {
public static final String SERVER_IP = "http://192.168.0.222/";
public static final String SERVICE_URL = SERVER_IP + "businesswebserviceNew/service.asmx";
public static final String CONTENT_TYPE_TEXT_XML = "text/xml; charset=utf-8";
public static final String GET_DATE_AND_TIME_URL = SERVICE_URL + "/GetDateAndTime";
}
Here is the SOAPClient.java class
public class SoapClient {
private static Logger log = LogManager.getLogger(SoapClient.class);
/*Input Stream Convert to the String Object*/
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public String ConsumeTheService(String SOAPXML, String APINAME) {
String Result = null;
try {
/*Create The Connection*/
URL url = new URL(KflConstants.SERVICE_URL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", KflConstants.CONTENT_TYPE_TEXT_XML);
conn.setRequestProperty(APINAME, KflConstants.GET_DATE_AND_TIME_URL);
log.info("Sending the envelope to server");
/*Send the request XML*/
OutputStream outputStream = conn.getOutputStream();
outputStream.write(SOAPXML.getBytes());
outputStream.close();
/* Read the response XML*/
log.info("Reading the Response");
InputStream inputStream = conn.getInputStream();
Result = convertStreamToString(inputStream);
inputStream.close();
/*INput Stream Convert to the SOAP Message*/
InputStream is = new ByteArrayInputStream(Result.getBytes());
SOAPMessage resposeSOAP = MessageFactory.newInstance().createMessage(null, is);
/*Return Values*/
log.info("Result SOAP:"+resposeSOAP.toString());
log.info("Result String:"+Result);
return Result;
} catch (Exception e) {
e.printStackTrace();
log.error(e);
return e.toString();
}
}
Thanks,
SoapRequestBuilder s = new SoapRequestBuilder();
s.Server = "127.0.0.1"; // server ip address or name
s.MethodName = "ConcatWithSpace";
s.XmlNamespace = "http://tempuri.org/";
s.WebServicePath = "/SimpleService/Service1.asmx";
s.SoapAction = s.XmlNamespace+s.MethodName;
s.AddParameter("one", "David");
s.AddParameter("two", "Hobbs");
String response = s.sendRequest();