i need to send some parameters to the API which accept as it seems only GET method...if i join parameters Im unable to send it through GET method and with POST method I'm getting 404 - not found for the call...
already tried different methods of joining parameters to the call but no luck
// Documentation - https://coinmarketcap.com/api/documentation/v1/#section/Quick-Start-Guide
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c"; // my temp key feel free to use it
HttpURLConnection urlConnection = null;
URL url = new URL("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("X-CMC_PRO_API_KEY", apiKey);
Map<String, String> parameters = new HashMap<>();
parameters.put("start", "1");
parameters.put("limit", "5000");
parameters.put("convert", "USD");
urlConnection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
urlConnection.connect();
int status = urlConnection.getResponseCode();
String message = urlConnection.getResponseMessage();
I would like to have results from API
The documentation only mention GET method. Add the parameters as standard HTTP GET parameters:
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c";
final String request = "start=1&limit=500&convert=USD";
HttpURLConnection urlConnection = null;
URL url = new URL("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?" + request);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("X-CMC_PRO_API_KEY", apiKey);
try (BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())))
{
String line = br.readLine();
while (line != null)
{
System.out.println(line);
line = br.readLine();
}
}
String apiKey = "707e6117-e462-4de3-9748-98ab6a467f0c"; // my temp key feel free to use it
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
RestTemplate restTemplate = new RestTemplate();
String url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("start", "1");
map.add("limit", "5000");
map.add("convert", "USD");
map.add("ReadTimeout", "10000");
map.add("ConnectTimeout", "15000");
map.add("X-CMC_PRO_API_KEY", apiKey);
System.out.println(map);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
System.out.println(response.getBody());
}
Related
Can someone explain me how to pass JSON parameter in request body.
I am using HttpURLConnection to create the connection, as below:
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");
JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
How can I put set the req body here?
For specifying the body of your request:
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()
Hello guys I am trying to send get request in java with header. I am looking for a method like conn.addHeader("key","value); but I cannot find it. I tried "setRequestProperty" method but it doest not work..
public void sendGetRequest(String token) throws MalformedURLException, IOException {
// Make a URL to the web page
URL url = new URL("http://api.somewebsite.com/api/channels/playback/HLS");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Authorization", "bearer " + token);
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
It returns Httpresponse 401 error.
My office mate use unity c# to send get request header his codes looks like the fallowing.
JsonData jsonvale = JsonMapper.ToObject(reqDataGet);
// Debug.Log(jsonvale["access_token"].ToString());
// /*
string url = "http://api.somewebsite.com/api/channels/playback/HLS";
var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) =>
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
}
break;
}
});
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "bearer " + jsonvale["access_token"].ToString());
request.Send();
Any help?
In Java I think you want something like this.
String url = "http://www.google.com/search?q=stackoverflow";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "My Example" );
int responseCode = con.getResponseCode();
I am trying to do a java rest web service using "POST" method.My client part to invoke the web service is working proper.But i am facing difficulty in accessing the passed parameters by "POST" method.Any help would be appreciable.
Here is my client side
public static void main(String[] args) throws IOException
{
String urlParameters = "param1=world¶m2=abc¶m3=xyz";
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}
And here is my java rest web service method to access the parameters(unable to access).
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public String getpostdata(#QueryParam("param1") String param1,#QueryParam("param2") String param2)
{
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",param1);
return jObjDevice.toJSONString();
}
When i run,I am getting
{"Hello":null} as json string instead of {"Hello":"world"}.Getting null means it is unale to access the passed parameters.Please do help.
You can use #QueryParam like shown below.
public String getpost( #QueryParam("param1") String param1,
#QueryParam("param2") String param2){
// Access both param below
}
To send data using POST request is quite straightforward.
Instead of conn.getOutputStream().write(postDataBytes); you'll have to use DataOutputStream to send data
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public static void main(String[] args) throws IOException
{
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("param1", "hello");
params.put("param2", "world");
JSONObject myJSON = new JSONObject(params);
System.out.println(myJSON);
byte[] postData = myJSON.toString().getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
//Try with Resources Example, just giving you an option
// try (DataOutputStream wr = new
// DataOutputStream(conn.getOutputStream()))
// {
// wr.write(postData);
// }
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
}
Note: You're sending application/json header in your request but I don't see a JSON in your code. It is advisable to send useful headers only
You can convert HashMap directly to JSONObject like,
org.json.JSONObject jsonObject = new org.json.JSONObject(params);
But this only works for Map<String, String>
To access the parameter in webservice, you'll have to accept JSONObject instead of accepting Map<String, String>.
public String getpost(JSONObject params) throws JSONException
{
if(params.has("param1"))
System.out.println(params.getString("param1"));
if(params.has("param2"))
System.out.println(params.getString("param2"));
//IMPLEMENT YOUR LOGIC HERE AND THEN RETURN STRING
return "your_return string";
}
I need to figure out a way to check if minecraft username and password is valid.
I have found this documentation which is telling a lot of things about the minecraft authentication : http://wiki.vg/Authentication
Looks like it needs a JSON HTTP POST Request but I have no idea how to do that :S
I have searched a lot and went through a lot of exemple but none of these works. The best result I had is no result printed in console or a 403 error.
Thanks
I figured out how to do it !
private static String MakeJSONRequest(String username, String password){
JSONObject json1 = new JSONObject();
json1.put("name", "Minecraft");
json1.put("version", 1);
JSONObject json = new JSONObject();
json.put("agent", json1);
json.put("username", username);
json.put("password", password);
return json.toJSONString();
}
private static String httpRequest(URL url, String content) throws Exception {
byte[] contentBytes = content.getBytes("UTF-8");
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
OutputStream requestStream = connection.getOutputStream();
requestStream.write(contentBytes, 0, contentBytes.length);
requestStream.close();
String response = "";
BufferedReader responseStream;
if (((HttpURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
}
response = responseStream.readLine();
responseStream.close();
if (((HttpURLConnection) connection).getResponseCode() != 200) {
//Failed to login (Invalid Credentials or whatever)
}
return response;
}
How to use it :
System.out.println(httpRequest(new URL("https://authserver.mojang.com/authenticate"), MakeJSONRequest("YourUsername", "YourPassword")));
I'm try to send Post request to Google elevation API and expecting response
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
private final String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true&key=<API KEY>";
URL obj = new URL(ELEVATION_API_URL);
java.net.HttpURLConnection con = (java.net.HttpURLConnection)obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I'm sending request in this manner but I'm getting response code as 400.This is working when request sent from browser. What is wrong with this code.
To Allow me to get XML back I made the following changes to your project
StringBuilder response = new StringBuilder(); // placed on the top of your Class
**wr.writeBytes(urlParameters.toString());** // as you have it in your code
System.out.println("ResponseMessage : " + connection.getResponseMessage());
System.out.println("RequestMethod : " + connection.getRequestMethod());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
wr.flush();
wr.close();
// I changed the URL to :
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/xml";
//**I get XML in the response**
return response.toString();
I think there is a problem with the url parameters.
Firstly because sending an empty elevation api request does return a code 400 (Invalid request. Missing the 'path' or 'locations' parameter.).
Secondly because this works (returning 200) :
public void test() throws Exception {
String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true";
URL obj = new URL(ELEVATION_API_URL + "?" + urlParameters);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
//String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
}