Hi I am trying to get the list of graphs in MarkLogic using RestTemplate.
Below is the sample code. From the browser I can able to get the graph list, but through the Java REST Client I am getting error 401.
HttpHeaders header = new HttpHeaders();
String plainCreds = "restadmin:restpassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
header.setAccessControlAllowCredentials(true);
header.add("Authorization", "Basic " + base64Creds);
header.setAccept(Arrays.asList(MediaType.TEXT_XML));
header.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<String>(header);
String url = "http://localhost:8003/v1/graphs";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println("Response : "+response.getStatusCode());
Please help me in resolving the issue
Try copying the HTTP auth code at https://github.com/rjrudin/ml-app-deployer/blob/master/src/main/java/com/rjrudin/marklogic/rest/util/RestTemplateUtil.java#L18 - I know it will handle HTTP basic auth against the management API on port 8002, and it should work fine on your REST API server on port 8003.
Related
I want to send to webdav server a 100 files in one request. I'm getting list of messages, then I creating binary body parts of them. This is my code which gets me 301 http error response code. When I send one file it's working but expected behaviour is to send parts of files. And I want it to be created one file by one on the server, is it possible?
CloseableHttpClient client = HttpClients.createDefault();
HttpPut httpPost = new HttpPut("http://localhost:8888/webdav"); // I also tried with / at the end
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
messages.forEach(m -> {
builder.addBinaryBody("file", new File(Paths.get(m.getPath()).toAbsolutePath().toString()),
ContentType.APPLICATION_OCTET_STREAM, m.getFileName() + ".encryptedByAes");
builder.addBinaryBody("file", new File(Paths.get(m.getAesPath()).toAbsolutePath().toString()),
ContentType.APPLICATION_OCTET_STREAM, m.getFileName() + ".aes");
});
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
UsernamePasswordCredentials creds
= new UsernamePasswordCredentials("test", "test");
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != HTTP_OK) {
throw new WebDavException("Error while executing request to webdav server with messages");
}
client.close();
I am using httpclient in org.apache.httpcomponents (version 4.5.2) for http post calls, the code I wrote:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.addHeader("content-type", "application/json");
StringEntity params = new StringEntity("param");
post.setEntity(params);
HttpResponse response = client.execute(post);
/***Other code section**/
cusmtomOtherFunction();
The problem is, I want to wait until the http post call has finished, then execute cusmtomOtherFunction(), how can I make this happen?
I want to send request through RestTemplate. But my url has braces ('{', '}'), and therefore I have exception: "Not enough variable values available to expand ...".
I try do it through uri
UriComponentsBuilder builder = UriComponentsBuilder.fromPath(url);
UriComponents uriComponents = builder.build();
URI uri = uriComponents.toUri();
But I got new exception:"protocol = https host = null".
How I can send request with my URL? In URL must be braces.
My code:
String url = "https://api.vk.com/method/execute?code=return[API.users.search({"count":1})];&access_token...
String result = restTemplate.getForObject(url, String.class);
Below code encrypts the uri using UriComponentsBuilder, adds query params using RestTemplate and also sets HttpHeaders if any.
public HttpEntity<String> getEntityByUri() {
String req = "https://api.vk.com/method/execute";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(req)
.queryParam("code",
"return[API.users.search({"count":1})]");
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> httpEntity = new HttpEntity<String>(headers);
return new RestTemplate().exchange(builder.build().encode().toUri(), HttpMethod.GET, httpEntity, String.class);
}
Hope this helps and good luck!
I am trying to hit .svc service from my JME application using POST method. but getting 'bad request'. Following is my code.
HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", ""+(postMsg.getBytes().length));
out = hc.openOutputStream();
out.write(postMsg.getBytes());
System.out.println("hc.getResponseCode() = "+hc.getResponseCode()+ " hc.getResponseMessage() = "+hc.getResponseMessage());
Please tell me what is wrong with the code.
Instead of http, I used Ksoap2-j2me-core jar with following code that i found -
SoapObject request = new SoapObject("namespace", "login");
request.addProperty("username", "pranav");
request.addProperty("password", "gangan");
//create the SOAP envelope
final SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.setOutputSoapObject(request);
//create the transport and then call
final HttpTransport httpTransport = new HttpTransport("http://URL");
httpTransport.call("\"login\"", env);
SoapObject body = (SoapObject) env.bodyIn;
//body.getProperty(0) will return the content of the first tag inside body
Object response = body.getProperty(0);
System.out.println(response.toString);
Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>