I'm trying to connect to the transmission rpc interface via C#/Java to get some informations back.
https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt
Unfortunatly I have problems to get the correct HTTP-Post to access the interface.
For example if I try this in C#:
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["torrent-get"] = "id";
var response = client.UploadValues("http://ip:9091/transmission/rpc", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine("" + responseString);
}
Or if i use:
using (var webClient = new WebClient())
{
String json = "{\"arguments\": {\"fields\": [ \"id\", \"name\", \"totalSize\" ],\"ids\": [ 7, 10 ]},\"method\": \"torrent-get\",\"tag\": 39693}";
var response = webClient.UploadString("http://192.168.240.171:9091/transmission/rpc", "POST", json);
Console.WriteLine(""+response);
}
I get the following error:
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The Remoteserver returned an exception: (409) conflict.
You must save the X-Transmission-Session-Id provided in the 409 response and resubmit the request with a X-Transmission-Session-Id property added to your request header.
Example in java :
int index = responseString.indexOf("X-Transmission-Session-Id:");
String sessionId = responseString.substring(index + 27, index + 75);
connection.setRequestProperty("X-Transmission-Session-Id", sessionId);
Related
So I am trying to make a HTTP request to get access token and refresh token using following java code.
String url = "https://oauth2.googleapis.com/token?";
Map<String, String> parameters = new HashMap<>();
parameters.put("code", "4%2******");
parameters.put("client_id", "*****");
parameters.put("client_secret", "*****");
parameters.put("redirect_uri", "http://localhost");
parameters.put("grant_type","authorization_code");
parameters.put("access_type","offline");
String form = parameters.keySet().stream()
.map(key -> key + "=" + URLEncoder.encode(parameters.get(key), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.headers("Content-Type", "application/json")
.POST(BodyPublishers.ofString(form)).build();
HttpResponse<?> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode() + response.body().toString());
But using this code gives the following error,
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\ncode=4%2****\n^",
"status": "INVALID_ARGUMENT"
}
}
What is the mistake that I have done here and should rectify in order to get proper results?
You are sending application/x-www-form-urlencoded data format but according to the response message you should send json. Try to change definition of form:
String form = new ObjectMapper().writeValueAsString(parameters);
I am trying to capture the graphql response from the network response tab using the selenium4 dev tool.
I have tried the below code and its prints all data from the 30 + requests available on the network response but I just want to fetch graphql file and print the response available with graphql request.
DevTools finalDevTools = devTools;
devTools.addListener(Network.responseReceived(), responseReceived -> {
requestIds[0] = responseReceived.getRequestId();
String url = responseReceived.getResponse().getUrl();
int status = responseReceived.getResponse().getStatus();
String type = responseReceived.getType().toJson();
String headers = responseReceived.getResponse().getHeaders().toString();
String responseBody = finalDevTools.send(Network.getResponseBody(requestIds[0])).getBody();
System.out.println(responseBody);
});
I have a node js server implementation and I would like to send some values to an Android (Java) client. The method of the node js server is as follows:
app.get('/GetValues*', function (request, response) {
// Request needs to be a GET
if (request.method == 'GET') {
var username = request.query.account;
var time_now = Date.now();
var db = database('./database.db');
var row_account = db.prepare('SELECT SCORE score, STARTED_STUDY_SERVER_MILLIS timestamp, DAYS_TOTAL days_total FROM ACCOUNTS WHERE NAME = ?').get(username);
var score = row_account.score;
var days_total = row_account.days_total;
var days_count = time_now - row_account.timestamp;
var minutes_count = time_now - row_account.timestamp;
var statement = db.prepare("UPDATE ACCOUNTS SET DAYS_COUNT = ?, MINUTES_COUNT = ? WHERE ID = ?");
statement.run(days_count,minutes_count,getAccountID(db, request.query.account));
var row_usage = db.prepare('SELECT DURATION_ENABLED duration_enabled, DURATION_DISABLED duration_disabled FROM USAGE WHERE NAME = ?').get(username);
var duration_enabled = row_usage.duration_enabled;
var duration_disabled = row_usage.duration_disabled;
}
});
I would like to send the values score (integer), days_total (integer), days_count (integer), minutes_count (long), duration_enabled (long), duration_disabled (long) to the client.
How can I send it to the client? I think response.send() only accepts strings. How can I parse the values in Java when received?
Since you need to send all those values at once, it's common to respond with a JSON in such a case. In express, you can send a JSON response using response.send() or response.json() like this:
app.get('/GetValues*', function (request, response) {
// ... your db operations here, then
response.json({
score: score,
days_total: days_total,
days_count: days_count,
minutes_count: minutes_count,
duration_enabled: duration_enabled,
duration_disabled: duration_disabled
});
});
This will send a response with Content-Type: application/json and a JSON string in the body looking like this:
{"score":12,"days_total":12,"days_count":12,"minutes_count":12,"duration_enabled":12,"duration_disabled":12}
Then you just parse it in your Java code.
By the way, this line
if (request.method == 'GET') {
is unnecessary. Registering a handler via app.get(), express will only handle GET requests anyway.
I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();
This may be easy one, but I am confused.
I am trying to do HTTP POST on a server using Android Restlet, and read the reply returned from the server.
I created form using:
Form form = new Form
form.add("msg" ,"This is my message");
Now, I have clientResource as follows:
ClientResource clientResource = new ClientResource("www.example.com/my-http-post-url/");
Now, I am doing HTTP Post as:
Representation response=null;
try{
response= clientResource.post(form.getWebRepresentation(null));
System.out.println("Got response !! , response : " + response.getText());
System.out.println( "Got Context: " + clientResource.getContext() );
System.out.println( "Got Response: " + clientResource.getResponse());
System.out.println( "Got Resonse Attribute : " + clientResource.getResponseAttributes() );
System.out.println( "Got Resonse Entity: " + clientResource.getResponseEntity() );
}catch(Exception e){
e.printStackTrace();
}
I found out that the code is going inside try, but its printing :
I/org.restlet( 493): Starting the default HTTP client
I/System.out( 493): Got response !! , response : null
I/System.out( 493): Got Context: null
I/System.out( 493): Got Response: HTTP/1.1 - OK (200) - OK
I/System.out( 493): Got Resonse Attribute : {org.restlet.http.headers=[(Date,Sun, 22 Jul 2012 22:14:03 GMT), (Server,WSGIServer/0.1 Python/2.7.1+), (Vary,Authorization), (Content-Type,application/json; charset=utf-8)]}
I/System.out( 493): Got Resonse Entity: [application/json,UTF-8]
I tried sniffing the data, to see if the server is replying or not, I am confident that server is sending the response content.
Can anyone tell me, how can I find out the response content send by the server?
You're using client-side support of Restlet the right way. The response content should be contained within the response representation...
The first step is to call your REST service outside Android to see the exact response content. Can you try to do this using restclient (http://code.google.com/p/rest-client/) or curl?
Thierry
Try something like this:
I have something similar to this right now:
ClientResource clientResource = new ClientResource(url);
Request request = new Request(Method.POST, url);
clientResource.setRequest(request);
Form form = new Form();
form.set("foo", "barValue");
org.restlet.representation.Representation response = clientResource.post(form, MediaType.APPLICATION_JSON);
Representation responseEntity = clientResource.getResponseEntity();
JsonRepresentation jsonRepresentation = new JsonRepresentation(responseEntity);
JSONObject jsonObject = jsonRepresentation.getJsonObject();
String[] names = JSONObject.getNames(jsonObject);
if (jsonObject.has("errorString"))
{
String error = jsonObject.optString("errorString");
}