I am getting connection refused exception when i am using the HttpClient to send the request but connection is established when i used the HttpUrlConnection. I want to use HttpClient but not able to figure out what is the reason for connection refusement as same thing works well when i use HttpUrlConnection.
Code when i use HttpClient
public static String httpGet(String urlStr) throws IOException {
HttpClient conn = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(urlStr);
HttpResponse response = conn.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent())
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
}
Code when i use HttpUrlConnection
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpsURLConnection conn =
(HttpsURLConnection) url.openConnection();
System.out.println("connection"+conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
Related
I'm going to use satang api with java.
This is reference book.
https://docs.satang.pro/authentication
I've completed public request code with java.
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Who can make private http request with any program language?
I have the same problem
But I use google sheet to import
function satang(){
var rows=[],obj_array=null;
try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.tdax.com/api/orders/?pair=btc_thb").getContentText());} catch (e) {obj_array=null;}
if (obj_array!=null){
for (r in obj_array) {rows.push([parseFloat(obj_array[r].bid),parseFloat(obj_array[r].price),parseFloat(obj_array[r].amount),parseFloat(obj_array[r].ask)]);}
var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Satang');ss.getRange("Satang!A1").setValue(new Date());
try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
if (rows==null||rows=="") {Browser.msgBox("Oops, no data from satang. Please try again"); return false;}
range=sheet.getRange(2,1,rows.length,4); range.setValues(rows);
}
}
public String placeLimitOrder(String amount,String pair,String price,String side) throws IOException, BadResponseException
{
Long lnonce=new Date().getTime();
String nonce=lnonce.toString();
String req="amount="+amount+"&nonce="+nonce+"&pair="+pair+"&price="+price+"&side="+side+"&type=limit";
String operation="orders/";
String signature=getSignature(req);
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
JsonObject obj=new JsonObject();
obj.addProperty("amount", amount);
obj.addProperty("nonce", nonce);
obj.addProperty("pair", pair);
obj.addProperty("price", price);
obj.addProperty("side", side);
obj.addProperty("type", "limit");
String json=obj.toString();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
I'm tring to connect "https://api.tdax.com/api/orders/?pair=btc_thb"
this url is working on chrome, postman.
I can connect this url with C#.
But ca'nt connect with java.
namespace Exchanges.Satang
{
class SatangApi
{
private static class WebApi
{
private static readonly HttpClient st_client = new HttpClient();
static WebApi()
{
st_client.Timeout = TimeSpan.FromSeconds(2);
}
public static HttpClient Client { get { return st_client; } }
public static string Query(string url)
{
var resultString = Client.GetStringAsync(url).Result;
return resultString;
}
}
public static string GetOrders(string symbol)
{
const string queryStr = "https://api.tdax.com/api/orders/?pair=";
var response = WebApi.Query(queryStr + symbol);
return response.ToString();
}
}
}
this C# code working well
but following java code not working, get 403 error.
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Some servers expect a User-Agent header to be present in the request to consider it as a valid request. So you need to add that to your request as follows.
con.setRequestProperty("User-Agent", "My-User-Agent");
int responseCode = con.getResponseCode();
The value of this header (My-User-Agent in the above example) can be set to any String you desire for this endpoint. For example, Postman sets something like PostmanRuntime/7.16.3 for this.
C# might be doing this internally, so you didn't have to set it explicitly.
public String getOrders(SatangCurrencyPairs currencyPair) throws IOException, BadResponseException {
String operation="orders/?pair="+currencyPair.toString();
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
I'm using this link that I've changed a little in order to get convert adress to GeoCodes :http://julien.gunnm.org/geek/programming/2015/09/13/how-to-get-geocoding-information-in-java-without-google-maps-api/
I don't understand for some requests I get 400 responseCode and for some i don't have any issue.(I tried these requests and they work fine for me).
For example:
private String getRequest(String url) throws Exception {
url=http://nominatim.openstreetmap.org/search=42+Avenue+Foch,+Saint+Maur+Des+Fossés+France&format=json&addressdetails=1
final URL obj = new URL(url);
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Length", Integer.toString(url.length()));
con.setRequestMethod("GET");
InputStream is ;
if (con.getResponseCode() != 200) {
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
I'm trying to send push notifications via Appcelerator rest API through my java server. I've been able to login, but when I try to send the notification I get 422 error (Unprocessable entity)
Here´s my login:
String SENDER_ID = "55694f177eead29359bda190";
String API_KEY = "bRhpzjfpHakUkYeVGbCBoFLGpqLTeKIm";
String API_USR = "tuin";
String API_PAS = "tuin123";
String URL_ACS = "https://api.cloud.appcelerator.com/v1/";
URL url = null;
URLConnection uc = null;
String idSession=null;
try {
url = new URL(URL_ACS+"users/login.json?key="+API_KEY+"&login="+API_USR+"&password="+API_PAS+"");
uc = url.openConnection();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
if (conn.getResponseCode() != 200) {
throw new Exception(conn.getResponseMessage());
}
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
String respuesta=sb.toString();
if(respuesta.contains("status\":\"ok") && respuesta.contains("code\":200") ){
int number=sb.indexOf("session_id");
String meta=sb.substring(number+13, number+60);
int fin=meta.indexOf("\"");
idSession=meta.substring(0, fin);
}else{
System.out.println("No ID");
}
} catch (Exception e) {
throw new Exception("Trouble "+e);
}
Then I try to send the notification
public String sendPush(String date,String name, String text, String title,String session_id) throws Exception{
String URL_ACS = "https://api.cloud.appcelerator.com/v1/";
String API_KEY = "bRhpzjfpHakUkYeVGbCBoFLGpqLTeKIm";
URL url = null;
HttpURLConnection uc = null;
String idSession=null;
try {
String rt=URL_ACS+"push_notification/notify.json?key="+API_KEY+"";
url=new URL(rt);
uc = (HttpURLConnection) url.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/json");
uc.setRequestProperty("Accept", "application/json");
uc.setRequestProperty("Cookie","_session_id="+session_id);
JSONObject cred = new JSONObject();
JSONObject push = new JSONObject();
JSONObject chan = new JSONObject();
cred.put("alert","test");
cred.put("title","title");
cred.put("icon","icon_notifi");
cred.put("vibrate",true);
cred.put("sound","default");
push.put("payload",cred);
//chan.put("push_notification", push);
System.out.println(push.toString());
String responseJSON=push.toString().replace("{\"payload\":", "{channel=\"noti\",to_ids=\"everyone\",payload=");
OutputStreamWriter wr= new OutputStreamWriter(uc.getOutputStream());
wr.write(responseJSON);
if (uc.getResponseCode() != 200) {
throw new Exception(uc.getResponseMessage());
}
InputStream is = uc.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
uc.disconnect();
System.out.println("The content was: " + sb.toString());
} catch (Exception e) {
throw new Exception("Trouble: "+e);
}
return idSession;
}
In the second part I got 422 Error.
I got the same problem. I fixed changing to Admin: yes the user that I'm using.
http://docs.appcelerator.com/arrowdb/latest/#!/guide/admin_access
I am using this code to send data to the site where my gae-python app is deployed .But I dont know how to receive it on the other end.
protected void tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter requestself = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("http://www.pranshutrial3.appspot.com");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
requestself = new OutputStreamWriter(connection.getOutputStream());
requestself.write(parameters);
requestself.flush();
requestself.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}