Twitter streaming API - Error 401 Unauthorized - api

Running a java main program to call twitter streaming api. I have generated a bearer token and passing to the api. But getting the error response Error 401 Unauthorized
Is passing the bearer token right way to authenticate? If not what is the right way to do this?
SSLConnectionSocketFactory sslsf = getSSLConnectionFactory();
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpHost target = new HttpHost("stream.twitter.com", 443, "https");
new BasicHttpContext();
HttpPost httpPost = new HttpPost("/1.1/statuses/filter.json");
StringEntity postEntity = new StringEntity("track=birthday","UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
//httpPost.setHeader("Authorization", "Bearer " + Base64.encodeBase64(bearerToken.getBytes()));
httpPost.setHeader("Authorization", "Bearer " + bearerToken);
httpPost.setHeader("User-Agent", "Your Program Name");
httpPost.setHeader("Host", "stream.twitter.com");
HttpResponse response = httpClient.execute(target, httpPost,new BasicHttpContext());
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
if(buffer.length()>30000) break;
}
System.out.println(buffer);
//return new EventImpl(buffer.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}

Related

Requesting a API token with both basic authentication and application/x-www-form-urlencoded

I'm trying to create an application using MS Visual Studio in either vb.net or C# to receive a token for a web api that has both basic authentication and application/x-www-form-urlencoded. When I send the request from Postman the requested works. Please see Postman screen shots below. When is use the below code I receive and message "Request failed with status code NotFound" back and the request fails. Can any point in the the right direction to resolve this.
Thank you
Postman
postman body
`private void button1_Click(object sender, EventArgs e)
{
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
//client.Timeout = -1;
RestRequest request = new RestRequest("post", Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials",true);
request.AddParameter("scope", "https://?????????",true);
RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}
}
`
I solved the problem. With the below code.
Uri baseurl = new Uri("https://api address/token");
RestClient client = new RestClient(baseurl);
RestRequest request = new RestRequest(baseurl, Method.Post);
request.AddHeader("Authorization", "Basic M2U4Y");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&scope=https://FED0C291",arameterType.RequestBody);RestResponse response = client.Execute(request);
if (response.Content == "")
{
textBox1.Text = response.ErrorException.Message ;
}
else
{
textBox1.Text = response.Content;
}

RESTSHARP errors ( IRestResponse, Method.GET, Execute)

public virtual string GetPaymentStatus(HttpContext context, NGeniusConfiguration configuration)
{
var reference = context.Request.Query[NGeniusConstants.ApiQueryStringRef].ToString();
var token = GetAccessToken(configuration);
var url = new Uri(GetPaymentBaseUrl(configuration), string.Format(NGeniusConstants.ApiUrl.OrderStatus, configuration.OutletId, reference));
var client = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", string.Format(NGeniusConstants.ApiauthorizationMode.Bearer, token));
request.AddHeader("accept", NGeniusConstants.ApiPaymentAcceptJson);
IRestResponse response =client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
var status = JsonConvert.DeserializeObject<NGeniusOrderStatusResponse>(response.Content);
return status.Embedded.Payment.First().State;
}
else
{
throw new Exception("Error while getting the order status", response.ErrorException);
}
}
I am fairly new to .Net Core. Can someone tell me why I have errors in Method.GET, IRestResponse and Execute? I have already included "using RestSharp;" in the program as well.
for more reference the the project i am implementing is from GITHUB.

ModSecurity: Access denied with code 403 (phase 1) using woocomerce rest api

I am trying to use woocommerce rest api to update product stock quantity and price, using PUT Method, but after running the code, it gives me error:
Response Code 403 Forbidden. You don't have permission to access /wc-api/v2/products/15542
on this server.
I am using centos 6 server, i have commented on modsecurity_crs_30_http_policy.conf [id "960032"] by researching on web. but still it doesnt work.
public void updateStock() {
String nonce = RandomStringUtils.randomAlphanumeric(32);
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("oauth_consumer_key", key);
paramMap.put("oauth_timestamp", "" + (System.currentTimeMillis() /
1000));
paramMap.put("oauth_nonce", nonce);
paramMap.put("oauth_signature_method", "HMAC-SHA1");
List<NameValuePair> qparams = new ArrayList<>();
for (Map.Entry<String, String> parameter : paramMap.entrySet()) {
qparams.add(new BasicNameValuePair(parameter.getKey(),
parameter.getValue()));
}
String encodedParams =
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC);
String signature = getSignature("http://topvacuumparts.com/wc-
api/v2/products/15542", encodedParams, "PUT");
qparams.add(new BasicNameValuePair("oauth_signature", signature));
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = URIUtils.createURI("http", "topvacuumparts.com", -1, "wc-
api/v2/products/15542", URLEncodedUtils.format(qparams, ENC), null);
HttpPut httpget = new HttpPut(uri);
httpget.setHeader("X-Stream", "true");
httpget.setHeader("Content-Type", "application/json");
JSONObject obj = new JSONObject();
JSONObject ob = new JSONObject();
obj.put("stock_quantity", "20");
ob.put("product", obj);
StringEntity entity1 = new StringEntity(obj.toString());
httpget.setEntity(entity1);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Response Code " +
response.getStatusLine().getStatusCode());
}
This is the Result:
Response Code 403
Json response
403 Forbidden
You don't have permission to access /wc-api/v2/products/15542
on this server

Post a string to restful webservice in C#

I am provided a webservice url similar to:
http://ericdev35:7280/persons/persons/
and a username and password.
I want to make a post call on this web service from WPF application.
The data to be sent to the service is the first name and last name of a person in the format:
"fname=Abc&lname=Xyz"
How can I make a call for this in C#?
Here is the code that I have tried:
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create("http://ericdev35:7280/persons/persons/");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Credentials = new NetworkCredential(username, password);
string data = "fname=Abc&lname=Xyz";
StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(data);
writer.Close();
This does not give me any error but I cannot see the data that I have posted. Is there anything that needs to be corrected?
Is the Content Type correct?
This Method posts json.
After that it gets the response and deserialize the Json Object.
private static string PostJson<T1>(string p_url, string p_json, string p_method, out T1 p_target)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(p_url);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = p_method;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(p_json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = ex.Response as HttpWebResponse;
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var a_result = streamReader.ReadToEnd();
//If you dont need a Json object delete anything behind here
try
{
p_target = JsonConvert.DeserializeObject<T1>(a_result);
}
catch { p_target = default(T1); }
return a_result;
}
}

2 exceptions when trying to make async HttpWebRequest

I am writing an MVC Web API the make async HttpWebRequest calls. I am getting 2 different exceptions. Below is the method I am using.
The 1st exception is: "This stream does not support seek operations." and it is happening on the responseStream.
The 2nd exception is: "timeouts are not supported on this stream" and that is happening on the MemoryStream content.
What am I doing wrong? I have been Googling but not really finding any solution.
Thanks,
Rhonda
private async Task GetHtmlContentAsync(string requestUri, string userAgent, string referrer, bool keepAlive, TimeSpan timeout, bool forceTimeoutWhileReading, string proxy, string requestMethod, string type)
{
//string to hold Response
string output = null;
//create request object
var request = (HttpWebRequest)WebRequest.Create(requestUri);
var content = new MemoryStream();
request.Method = requestMethod;
request.KeepAlive = keepAlive;
request.Headers.Set("Pragma", "no-cache");
request.Timeout = (Int32)timeout.TotalMilliseconds;
request.ReadWriteTimeout = (Int32)timeout.TotalMilliseconds;
request.Referer = referrer;
request.Proxy = new WebProxy(proxy);
request.UserAgent = userAgent;
try
{
using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
{
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
await responseStream.CopyToAsync(content);
}
}
var sr = new StreamReader(content);
output = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
output = string.Empty;
var message = ("The API caused an exception in the " + type + ".\r\n " + requestUri + "\r\n" + ex);
Logger.Write(message);
}
return output;
}
I fixed the issue by adding
content.Position = 0
before new StreamReader line. Now I just need to get it work with GZip compression.
Rhonda