I'm trying to implement Twitter's Retweet API to retweet a specific tweet. But I'm having AuthFailureError while requesting that API. I'm unable to solve this issue and stuck for many days. Any help would be appreciated.
Code:
private fun retweetTweet(tweetId: String) {
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Please wait")
progressDialog.show()
val jsonObject = JSONObject()
jsonObject.put("tweet_id", "$tweetId")
val url = "https://api.twitter.com/2/users/$userId/retweets"
Log.d(TAG, "retweetTweet: url: $url")
Log.d(TAG, "retweetTweet: tweet_id: $tweetId")
Log.d(TAG, "retweetTweet: userId: $userId")
val jsonObjReq: JsonObjectRequest =
object : JsonObjectRequest(Method.POST, url, jsonObject, Response.Listener { response ->
progressDialog.dismiss()
Log.d(TAG, "retweetTweet: $response")
try {
Log.d(TAG, "retweetTweet: ")
} catch (e: Exception) {
Log.e(TAG, "retweetTweet: ", e)
}
}, Response.ErrorListener { error ->
progressDialog.dismiss()
Log.e(TAG, "retweetTweet: ", error)
}) {
override fun getHeaders(): MutableMap<String, String> {
val headers: MutableMap<String, String> = HashMap()
val auth = "${Constants.TWITTER_BARRIER_TOKEN_KEY}"
headers["Authorization"] = auth
return headers
}
}
jsonObjReq.retryPolicy = DefaultRetryPolicy(5000, 3, 1.0f)
Volley.newRequestQueue(this).add(jsonObjReq)
}
Screenshot Of Error:
Related
I am trying to use BLOC inside my login page.. but I always get paused on exception that say Exception has occurred. _TypeError (type 'List<LoginRespon>' is not a subtype of type 'String') here is the code
isClick == true
? StreamBuilder(
initialData: bloc.inData(_name.text,_password.text),
stream: bloc.loginData,
builder: (context,
AsyncSnapshot snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
print('ppp ');
return Text('ok');
} else
return Text(snapshot.error
.toString());
})
: RaisedButton(
child: Text('Login'),
onPressed: () {
setState(() {
isClick = true;
});
},
),
and here is bloc file
class MyBLoc{
final _repository = Repository();
final _loginController = StreamController<String>();
Stream<String> get loginData => _loginController.stream;
final _name = BehaviorSubject<String>();
final _password = BehaviorSubject<String>();
saving(){
_repository.saving(_name.value,_password.value);
}
inData(String name, String password) async {
// I get paused on exception inside this method...
String result = await _repository.saving(name, password);
_loginController.sink.add(result);
}
dispose(){
_input.close();
_loginController.close();
_password.close();
}
}
final bloc = MyBLoc();
here is my repository file
class Repository{
static final userAPIProvider = UserProvider();
Future saving(String name, String password) => userAPIProvider.saving(name, password);
}
and here is my provider
class UserProvider {
final _url = '...';
Future<List<LoginRespon>> saving(String name, String password) async {
List<LoginRespon> datalogin = [];
try {
bool trustSelfSigned = true;
HttpClient httpClient = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) => trustSelfSigned);
IOClient client = new IOClient(httpClient);
print("cek");
final response = await client.post(_url,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode({
"name": name,
"pas": password,
}));
Map<String, dynamic> responseJson = json.decode(response.body);
if (responseJson["status"] == "200") {
datalogin.add(LoginRespon(
status: responseJson['status'],
data: Data(
name: responseJson['data']['name'],
status: responseJson['data']['status'])));
return datalogin;
} else {
print("ppp");
}
} on Exception {
rethrow;
}
return datalogin;
}}
and for my LoginRespon model is available here how to create a list from json string in flutter
Paused on exception happens inside bloc file in inData method is there a way to resolve this problem Exception has occurred. _TypeError (type 'List<LoginRespon>' is not a subtype of type 'String')
In MyBloc, the returned value is supposed to be String
String result = await _repository.saving(name, password);
But it's not the case with the following line in the repository
Future saving(String name, String password) => userAPIProvider.saving(name, password);
It's returning List<LoginRespon>
I am writing a Node JS SOAP client using Node-Soap module to send a file to a remote SharePoint based Web Services.
The machine client requires a proxy to access Internet and the SharePoint WS requires an account (user, pwd). Below are the code source.
However, I always have the error "(node:20857) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Cannot parse response".
Someone can help me, please?
var process = require('process');
var fs = require('fs');
var request = require('request')
var soap = require('soap');
var apiWSDL = '.../test-collab/WS/_vti_bin/copy.asmx?wsdl';
function sendFile() {
var p = new Promise(function (resolve, reject) {
request_with_defaults = request.defaults({
'proxy': 'http://***:***#10.115.108.109:8080',
'timeout': 50000,
'connection': 'keep-alive'
});
var options = {
'request': request_with_defaults,
endpoint: 'https://.../test-collab/WS/_vti_bin/copy.asmx',
}
var byteArray = fs.readFileSync('test.txt').toString('base64');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
//process.env.https_proxy = 'http://***#***:10.115.108.109:8080';
soap.createClient(apiWSDL, options, function (err, client) {
if (err) throw new Error(err);
var args = {
DestinationUrls: 'https://.../test-collab/WS/CAS/test.txt',
Stream: byteArray
}
client.setSecurity(new soap.ClientSSLSecurity(null, null, null, { /*default request options like */
strictSSL: false,
rejectUnauthorized: false,
// hostname: 'some-hostname'
//secureOptions: constants.SSL_OP_NO_TLSv1_2,
forever: true,
}));
client.addHttpHeader('vm6_webapp', 'SERVICE');
client.addHttpHeader('vm6_password', '***');
client.addHttpHeader('vm6_user', '***');
client.CopyIntoItems(args, function (err, result) {
//console.log(err);
if (err) {
console.log(err);
reject(err);
}
var sets;
try {
console.log(result);
if (result.length) {
resolve(result);
} else {
reject(result);
}
} catch (error) {
console.log("error");
reject("error und")
}
});
});
});
return p;
}
As the error message is Cannot parse response, two possibilities can happen:
either the response is not in XML format
or the XML response is not acceptable by SOAP response message defined in wsdl.
Can you redo the SOAP request by using an existing client, such as, SoapUI to confirm?
Otherwise, I propose to use console.error( err.stack ) rather than console.log( err ) to get the full execution trace of err.
Thank Nghia for your reply.
In fact, I've written a SOAP client in Java for this WebServers before and it works. That means the paramters are ok as well as the XML response is ok.
Here are the code in Java:
MoccaClient clientWSMocca = new MoccaClient();
CopySoap copySoap = (CopySoap)clientWSMocca.getClient(site_soap_url,
proxy_host, proxy_port, proxy_user, proxy_password,
mocca_user, mocca_password, mocca_web_app,
CopySoap.class);
// Récupération sous forme de tableau de bytes du fichier
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
InputStream in = new BufferedInputStream(new FileInputStream(file_path));
BufferedOutputStream bufOut = new BufferedOutputStream(out);
for (int b = in.read(); b != -1; b = in.read()) {
bufOut.write(b);
}
in.close();
bufOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Initialisation des variables de contexte
FieldInformation fieldInformation = new FieldInformation();
String destinationUrl = site_url + file_name;
DestinationUrlCollection destinationUrlCollection = new DestinationUrlCollection();
destinationUrlCollection.getString().add(destinationUrl);
FieldInformationCollection fieldInformationCollection = new FieldInformationCollection();
fieldInformationCollection.getFieldInformation().add(fieldInformation);
Holder<CopyResultCollection> copyResult= new Holder<CopyResultCollection>();
Holder<Long> getItemResult = new Holder<Long>();
copySoap.copyIntoItems(file_path, destinationUrlCollection, fieldInformationCollection, out.toByteArray(), getItemResult, copyResult);
MoccaClient.java
public class MoccaClient {
public Object getClient(String url,
String proxyhost, int proxyport, String userproxy, String passwordproxy,
String moccauser, String moccapassword, String moccawebapp,
Class<?> serviceclass) {
System.setProperty("org.apache.cxf.JDKBugHacks.defaultUsesCaches", "true");
boolean bssl = false;
if (url.startsWith("https")) {
bssl = true;
}
if (url.startsWith("HTTPS")) {
bssl = true;
}
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.getInInterceptors().add(new MyInterceptor());
factory.setServiceClass(serviceclass);
factory.setAddress(url);
Object client = factory.create();
Client clientDuProxy = ClientProxy.getClient(client);
Map<String, List<String>> headers = new HashMap();
headers.put("vm6_user", Arrays.asList(moccauser));
headers.put("vm6_password", Arrays.asList(moccapassword));
headers.put("vm6_webapp", Arrays.asList(moccawebapp));
clientDuProxy.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
HTTPConduit http = (HTTPConduit)clientDuProxy.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
http.setClient(httpClientPolicy);
if (proxyhost != null) {
http.getClient().setProxyServer(proxyhost);
http.getClient().setProxyServerPort(proxyport);
}
if (userproxy != null) {
http.getProxyAuthorization().setUserName(userproxy);
http.getProxyAuthorization().setPassword(passwordproxy);
}
if (bssl) {
TrustManager[] trustCerts = new TrustManager[]{new AllTrust()};
TLSClientParameters tcp = new TLSClientParameters();
tcp.setTrustManagers(trustCerts);
tcp.setSecureSocketProtocol("TLS");
tcp.setDisableCNCheck(true);
http.setTlsClientParameters(tcp);
}
return client;
}
}
I am trying to run the following code:
public class Item
{
[JsonProperty(PropertyName = "api-key")]
public string apikey { get; set; }
}
[[some method]]{
var url = "https://[search service name].search.windows.net/indexes/temp?api-version=2016-09-01";
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Put,url))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var sItem = new Item { apikey = [AzureSearchAdminKey] };
var tststring = JsonConvert.SerializeObject(sItem);
var body=new StringContent(tststring, Encoding.UTF8,"application/json" );
request.Content = body;
request.Method = HttpMethod.Put;
using (HttpResponseMessage response = httpClient.SendAsync(request).Result)
{
var stringr = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(stringr);
Console.ReadLine();
}
}
}
}
I get the following error:
"Error reading JObject from JsonReader. Path '', line 0, position 0."
Could someone from search team tell me what I did wrong?
The api key should be in the HTTP header, and the index definition should be in the HTTP body.
Here's some sample code for creating a data source, index, and indexer, which reads from an Azure SQL DB and indexes its rows.
class Program
{
static void Main(string[] args)
{
var searchServiceName = "[search service name]";
var apiKey = "[api key]";
var dataSourceName = "[data source name]";
var indexName = "[index name]";
var indexerName = "[indexer name]";
var azureSqlConnectionString = "[Azure SQL connection string]";
var azureSqlTableName = "[table name]";
using (var httpClient = new HttpClient())
{
var dataSourceDefinition = AzureSqlDatasourceDefinition(azureSqlConnectionString, azureSqlTableName);
var putDataSourceRequest = PutDataSourceRequest(searchServiceName, apiKey, dataSourceName, dataSourceDefinition);
Console.WriteLine($"Put data source {putDataSourceRequest.RequestUri}");
Console.WriteLine();
var putDataSourceResponse = httpClient.SendAsync(putDataSourceRequest).Result;
var putDataSourceResponseContent = putDataSourceResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(putDataSourceResponseContent);
Console.WriteLine();
var indexDefinition = IndexDefinition();
var putIndexRequest = PutIndexRequest(searchServiceName, apiKey, indexName, indexDefinition);
Console.WriteLine($"Put index {putIndexRequest.RequestUri}");
Console.WriteLine();
var putIndexResponse = httpClient.SendAsync(putIndexRequest).Result;
var putIndexResponseContent = putIndexResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(putIndexResponseContent);
Console.WriteLine();
var indexerDefinition = IndexerDefinition(dataSourceName, indexName);
var putIndexerRequest = PutIndexerRequest(searchServiceName, apiKey, indexerName, indexerDefinition);
Console.WriteLine($"Put indexer {putIndexerRequest.RequestUri}");
Console.WriteLine();
var putIndexerResponse = httpClient.SendAsync(putIndexerRequest).Result;
var putIndexerResponseContent = putIndexerResponse.Content.ReadAsStringAsync().Result;
Console.WriteLine(putIndexerResponseContent);
Console.WriteLine();
var runIndexerRequest = RunIndexerRequest(searchServiceName, apiKey, indexerName);
Console.WriteLine($"Run indexer {runIndexerRequest.RequestUri}");
Console.WriteLine();
var runIndexerResponse = httpClient.SendAsync(runIndexerRequest).Result;
Console.WriteLine($"Success: {runIndexerResponse.IsSuccessStatusCode}");
Console.ReadLine();
}
}
static HttpRequestMessage PutDataSourceRequest(string searchServiceName, string apiKey, string dataSourceName,
string datasourceDefinition)
{
var request = new HttpRequestMessage(HttpMethod.Put,
$"https://{searchServiceName}.search.windows.net/datasources/{dataSourceName}?api-version=2016-09-01");
request.Headers.Add("api-key", apiKey);
var body = new StringContent(datasourceDefinition, Encoding.UTF8, "application/json");
request.Content = body;
return request;
}
static HttpRequestMessage PutIndexRequest(string searchServiceName, string apiKey, string indexName,
string indexDefinition)
{
var request = new HttpRequestMessage(HttpMethod.Put,
$"https://{searchServiceName}.search.windows.net/indexes/{indexName}?api-version=2016-09-01");
request.Headers.Add("api-key", apiKey);
var body = new StringContent(indexDefinition, Encoding.UTF8, "application/json");
request.Content = body;
return request;
}
static HttpRequestMessage PutIndexerRequest(string searchServiceName, string apiKey, string indexerName,
string indexerDefinition)
{
var request = new HttpRequestMessage(HttpMethod.Put,
$"https://{searchServiceName}.search.windows.net/indexers/{indexerName}?api-version=2016-09-01");
request.Headers.Add("api-key", apiKey);
var body = new StringContent(indexerDefinition, Encoding.UTF8, "application/json");
request.Content = body;
return request;
}
static HttpRequestMessage RunIndexerRequest(string searchServiceName, string apiKey, string indexerName)
{
var request = new HttpRequestMessage(HttpMethod.Post,
$"https://{searchServiceName}.search.windows.net/indexers/{indexerName}/run?api-version=2016-09-01");
request.Headers.Add("api-key", apiKey);
return request;
}
static string AzureSqlDatasourceDefinition(string connectionString, string tableName)
{
return #"
{
""description"": ""azure sql datasource"",
""type"": ""azuresql"",
""credentials"": { ""connectionString"": """ + connectionString + #""" },
""container"": { ""name"": """ + tableName + #""" },
""dataChangeDetectionPolicy"": {
""#odata.type"": ""#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"",
""highWaterMarkColumnName"": ""highwatermark""
},
""dataDeletionDetectionPolicy"": {
""#odata.type"": ""#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"",
""softDeleteColumnName"": ""deleted"",
""softDeleteMarkerValue"": ""true""
}
}
";
}
static string IndexDefinition()
{
return #"
{
""fields"": [
{
""name"": ""id"",
""type"": ""Edm.String"",
""key"": true,
""searchable"": true,
""sortable"": true,
""retrievable"": true
},
{
""name"": ""field1"",
""type"": ""Edm.String"",
""searchable"": true,
""retrievable"": true
},
{
""name"": ""field3"",
""type"": ""Edm.Int32"",
""retrievable"": true
}
]
}
";
}
static string IndexerDefinition(string dataSourceName, string indexName)
{
return #"
{
""description"": ""indexer for azure sql datasource"",
""dataSourceName"": """ + dataSourceName + #""",
""targetIndexName"": """ + indexName + #""",
""schedule"": { ""interval"": ""P1D"" }
}
";
}
}
The indexer is scheduled to run once per day. You can set it to run more frequently if the data changes often, but it might affect your search throughput.
This is the table definition if you're interested
CREATE TABLE [dbo].[testtable](
[id] [int] IDENTITY(1,1) NOT NULL,
[field1] [nchar](10) NULL,
[field2] [nchar](10) NULL,
[field3] [int] NULL,
[highwatermark] [timestamp] NOT NULL,
[deleted] [bit] NOT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[testtable] (field1, field2, field3, deleted) VALUES ('abc', 'def', 123, 0)
It looks like you're trying to modify your index definition, but the body of the request contains the api-key instead of the JSON for the index definition. The api-key needs to be in the request headers, not the body.
You might find it simpler to use the Azure Search .NET SDK instead of calling the REST API directly.
a have UWP app, that working correctly. Now i working on .Net Standard Library providing same function and i do not now, what I'm doing wrong.
UWP code (working correctly)
private async void btnRVM_ClickR(object sender, RoutedEventArgs e)
{
using (HttpClient httpClient = new HttpClient())
{
Uri uri = new Uri("http://examplecom/api/Account/Register");
HttpContent content = new StringContent(JsonConvert.SerializeObject(new RegistrationObject(tbxUsername.Text, tbxPassword.Text, tbxConfirm.Text)), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await httpClient.PostAsync(uri, content);
}
catch (Exception e1)
{
string excMessage = e1.ToString();
}
}
But almost same code in .Net standard library do not working
public static async Task<object> RegisterAsync(string username, string password, string confirmPassword)
{
using (HttpClient httpClient = new HttpClient())
{
Uri uri = new Uri("http://example/api/Account/Register");
HttpContent content = new StringContent(JsonConvert.SerializeObject(new RegistrationObject(username, password, confirmPassword)), Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await httpClient.PostAsync(uri, content);
}
catch (Exception e1)
{
string excMessage = e1.ToString();
}
return Task.FromResult<object>(null);
}
}
When i am executing this via curl its working :
curl -u -X DELETE -H 'accept:application/json' http://localhost:13000/test/test_userid"
I made a common function which accept methodtype ( GET, POST, DELETE etc) and content type( JASON, TEXT ) for the httpbuilder.
def public httpRequest(String url, String content, Method requestType, ContentType contentType)
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType,contentType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
Now if i make a POST request , its working.
However if i make a GET or DELETE request using
def response = httpRequest(url,"",DELETE,JSON)
or
def response = httpRequest(url,"",GET,TEXT)
its shows the following error :-
error[message:Cannot set a request body for a DELETE/GET method, class:class java.lang.IllegalArgumentException
Do i need to make a separate function for GET/DELETE?
because
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
WORKS
Delete and Get wont accept Body , hence the solution is to make a check and execute accordingly
if(requestType.equals(DELETE)||requestType.equals(GET))
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
headers.Accept = 'application/json'
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
else
<---post request -->