I want to execute the below command through Java code. This is to create connection to my Appdynamics Contoller
curl --user user#customer1:password 'http://192.168.1.11:9090/controller/rest/applications?output=JSON'
The java code that I have written for this is
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Test {
private static HttpClient client;
public static void main(String[] args) {
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope("192.168.1.11", 9090), new UsernamePasswordCredentials(
"user", "password"));
httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
HttpPost httpget = new HttpPost("http://192.168.1.11:9090/controller/rest/applications?output=JSON");
System.out.println("Executing request " + httpget.getRequestLine());
response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I keep on getting below error
HTTP/1.1 401 Unauthorized
Error report HTTP Status 401 - type Status reportmessagedescriptionThis request requires HTTP authentication ().
Can anyone please help.
Related
I am trying to build a multipart HttpRequest using Java 11 as below. I am also trying to pass username
and password and later i might need a file also in the same request. However i keep getting 415 or 400 bad request errors.
The code is below.
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Client{
private HttpClient httpClient;
private HttpResponse httpResponse;
private String Response;
private Map<Object, Object> urlParameters;
public Client(String URL) {
httpClient=BuildClient(URL);
urlParameters= new HashMap<>();
urlParameters.put("username","xxxx");
urlParameters.put("password","xxxx");
try {
PostRequest(httpClient,URL,urlParameters);
} catch (IOException e) {
System.out.println("Client Error");
e.printStackTrace();
}
}
public HttpClient BuildClient(String URL) {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
//This is the code for request build
public HttpResponse PostRequest(HttpClient httpClient, String url, Map<Object, Object> params) throws IOException {
String boundary = new BigInteger(256, new Random()).toString();
HttpRequest request = HttpRequest.newBuilder()
//.POST(HttpRequest.BodyPublishers.fromPublisher(subscriber -> ))
.POST(HttpRequest.BodyPublishers.noBody())
.POST(HttpRequest.BodyPublishers.ofString("{\"username\":\"XXXXX\"}{\"password\":\"XXXX\"}"))
//.POST(HttpRequest.BodyPublishers.ofFile(Path.of("")))
.uri(URI.create("http://example.com/request/add"))
.setHeader("User-Agent", "firefox")
.setHeader("Content-Type", "multipart/form-data")
.build();
HttpResponse<String> response = null;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(request.headers());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
return response;
}
public HttpRequest.BodyPublisher FormatData(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if(builder.length()>0)
{
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
return HttpRequest.BodyPublishers.ofString(builder.toString());
//return null;
}
}
I was wandering if can be done without add some library as maven dependency such as apache HTTP client.
I have an encoding issue downloading a Chinese RSS url http://finance.qq.com/stock/ggjj/rss_ggjj.xml
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Test {
public static void main(String[] args) {
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
String url = "http://finance.qq.com/stock/ggjj/rss_ggjj.xml";
response = httpclient.execute(new HttpGet(url));
System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The output contains bad encoded characters:
... �ㄨ����搴�锛�涓��ㄤ�娉煎��������姘� ...
I'm trying to send https post request to my api that send json response, this is a search function so it will require 1 parameter, but i cannot get the expected result from my api, here are my code
Handler.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class Handler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public Handler(){
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params2 = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params2, schemeRegistry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params2);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if(method == POST){
HttpPost httpPost = new HttpPost(url);
if(params != null){
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error : " + e.toString());
}
return response;
}
makeServiceCall is used to make the request to url, but it only works with GET request and couldnt work with POST request, how do i fix this?
I need to integrate Kii MbaaS services in one of my web application apart from the Mobile apps. I was using the Android SDK and was able to connect it. However for website using Java solution they don't have any SDK and asked me to do th operation using REST. Now I was planning to use ApacheHttpClient from a Servlet to connect to the REST services. The REST format from their docs is given below. In ApacheHttpClient I know I can pass the headers(-H) as HttpGet.addHeader("content-type", "application/json"). However I am not sure how to pass the data (-d). Can anyone help me here by pointing to any tutorial link or any sample code on how to pass data to a REST service along with headers?
The REST syntax is given below-
curl -v -X POST \
-H "content-type:application/json" \
-H "x-kii-appid:{APP_ID}" \
-H "x-kii-appkey:{APP_KEY}" \
"https://api.kii.com/api/oauth2/token" \
-d '{"username":"user_123456", "password":"123ABC"}'
Thanks in advance.
------------------------- Edit--------------------------------------------------
here is a sample java code I wrote to connect to using Apache HttpClient 4.3 library however I keep getting error as 400... can anyone pls advice?
error -
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP
error code : 400 at
com.app.test.RestClientTest.main(RestClientTest.java:49)
package com.app.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class RestClientTest {
/**
* #param args
*/
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpost = new HttpPost("https://api.kii.com/api/oauth2/token");
httpost.addHeader("content-type", "application/json");
httpost.addHeader("x-kii-appid", "xxxxx");
httpost.addHeader("x-kii-appkey", "xxxxxxxx");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "xxxxx"));
nvps.add(new BasicNameValuePair("password", "xxxxx"));
// StringEntity input = new
// StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
// input.setContentType("application/json");
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
response = httpClient.execute(httpost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
Ok I got it solved. I need to wrap up the data in json format stringentity and post it and it will work.
Here I am posting the same for others who are planning to use the Kii MbaaS in their web apps apart from the Mobile app.
package com.app.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class RestClientTest {
/**
* #param args
*/
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://api.kii.com/api/oauth2/token");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/json"));
nvps.add(new BasicNameValuePair("x-kii-appid", "xxxxx"));
nvps.add(new BasicNameValuePair("x-kii-appkey", "xxxxxxxxxxxxxx"));
StringEntity input = new StringEntity("{\"username\": \"dummyuser\",\"password\": \"dummypassword\"}");
input.setContentType("application/json");
httpPost.setEntity(input);
for (NameValuePair h : nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
I use the following class to send an http request and get the returning XML response in my android project.
But the UnknownHostException is thrown when it trying to send the request.
Please help me on this problem.
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.util.Xml;
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
String s=e.toString();
System.out.println(s);
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
System.out.println(result);
}
}
Make sure you have declared the INTERNET permission in the AnroidManifest file, and have internet connection.
You should have this permission declared in AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />