I have a problem. I met only once. My code algoritm is designed requesting only one time.
But a request was received twice by server. I must produce a solution.
I think, this problem likes this url But I cant find anything(bug or question) about httpurlconnection?
Device's Android Version is 4.0.3 and Connection Method is GET.
try {
String encoding = session.getPlatform().getEncodingIse();
if (TradeUtil.isApachiClientActive()) {
HttpResponse hr = XHttpClientFactory.getConnectionResponse(session.getPlatform(), TradeServiceType.ISE, command);
if (!session.getPlatform().isUseStaticEncodingForIse()) {
encoding = XHttpClientFactory.getEncoding(hr, encoding);
}
strRtn = TradeUtil.getResponse(hr.getEntity().getContent(), encoding);
} else {
con = TradeUtil.createConnection(session.getPlatform(), TradeServiceType.ISE, command);
if (!session.getPlatform().isUseStaticEncodingForIse()) {
encoding = TradeUtil.getEncoding(con, session.getPlatform().getEncodingIse());
}
strRtn = TradeUtil.getResponse(con.getInputStream(), encoding);
}
} catch (Exception e) {
TradeUtil.toConsole(e);
response.getResponseResult().setResponseCode(ResponseResult.CONNECTION_ERROR);
response.getResponseResult().setDescription(e.getMessage());
try {
if (con != null)
con.disconnect();
} catch (Exception ex) {
}
return response;
}
public static HttpURLConnection createConnection(Platform platform,
TradeServiceType serviceType, String command) throws Exception {
command = command + "&MTXTimeAnd=" + Calendar.getInstance().getTimeInMillis(); // Cachlemeyi
// Engellemek
// için
TradeUtil.initSSLContext(); // Zoom ve ustundeki makinalar için SSL
// handshake için trust manager set etmek
// gerekiyor.
System.setProperty("http.keepAlive", "false");// Yatirim finansman +
// Android 2.2 Bug için
// gerekli
System.setProperty("https.keepAlive", "false"); // Yatirim finansman +
// Android 2.2 Bug için
// gerekli
HttpURLConnection con;
String methodType;
String encoding;
String strAdd = null;
if (serviceType.equals(TradeServiceType.ISE)) {
strAdd = platform.getIseServiceAdress();
methodType = platform.getIseConnectionMethodType();
encoding = platform.getEncodingIse();
} else if (serviceType.equals(TradeServiceType.TURKDEX)) {
strAdd = platform.getTurkdexServiceAdress();
methodType = platform.getTurkdexConnectionMethodType();
encoding = platform.getEncodingTurkdex();
} else {
throw new IllegalArgumentException("hatali service tipi");
}
if (methodType.equalsIgnoreCase("GET")) {
strAdd = strAdd + "?" + command;
}
URL adress = new URL(strAdd);
if (adress.getProtocol().equalsIgnoreCase("https")) {
con = (HttpsURLConnection) adress.openConnection();
((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} else {
con = (HttpURLConnection) adress.openConnection();
}
con.setUseCaches(false);
con.setReadTimeout(platform.getConnectionTimeout());
con.setConnectTimeout(platform.getConnectionTimeout());
if (methodType.equalsIgnoreCase("POST")) {
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(con.getOutputStream(), encoding);
osw.write(command);
osw.flush();
osw.close();
osw = null;
} catch (Exception ex) {
TradeUtil.toConsole(ex);
try {
if (osw != null)
osw.close();
} catch (Exception ex2) {
TradeUtil.toConsole(ex);
}
throw ex;
}
} else {
}
return con;
}
Related
After execution for 5 to 6 times i am not able to get response and the message is also not going to gateway and the application get struck.At InputStreamReader i am not able to get any response after execution for 5 times.When i checked the logs no error is coming but the Input Stream is not printing.
XMLFunctions.java
public static String getLocalCurtainControlResponse( String ipadress, String imvgid, String deviceid, String command, String value, int slidedValue) {
String result = null;
BufferedReader reader =null;
System.out.println("getLocalCurtainControlResponse : IN");
System.out.println("command : " + command);
System.out.println("value : " + value);
byte[] loginBytes = ("admin" + ":" + "admin").getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL("http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
System.out.print("step0"+"http://" + ipadress + "/cgi-bin/WebInterface.cgi?ImvgId=" + imvgid + "%20&DeviceId=" + deviceid + "%20&Action=" + command + "%20&Value=" + value + "%20&Level=" + slidedValue + "%20&App=MID");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
connection.addRequestProperty("Authorization", loginBuilder.toString());
// connection.connect();
InputStream in = connection.getInputStream();
System.out.print("step1"+connection);
StringBuilder sb = new StringBuilder();
System.out.print("step2"+sb);
reader = new BufferedReader(new InputStreamReader(in));
System.out.print("step3"+reader);
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
System.out.print("step4"+sb);
reader.close();
result = sb.toString();
System.out.print("step5"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("Hiiiiiiiiiiiiiiiiiiii"+e.getMessage());
} catch (IOException e) {
e.printStackTrace();
System.out.print("Byeeeeeeeeee"+e.getMessage());
} finally {
if (null!=reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.print("Hellllloooooooo"+e.getMessage());
}
}
}
return result;
}
Find the solution Post and Get using HttpUrlConnection
private Object doSendRequest(final int requestCode, String url, final Object params, final String sessionId, final String requestType, final Activity parentActivity) {
URL myurl;
Log.v("sessionId", sessionId + "");
HttpsURLConnection httpsURLConnection = null;
try {
if (requestType.equalsIgnoreCase("GET")) {
if (params.toString().length() >= 1) {
if (url.contains("?")) {
url = (url + params.toString());
} else {
url = (url + "?" + params.toString());
}
}
}
myurl = new URL(url);
Log.v("RequestCode, URL", requestCode + " : " + url);
httpsURLConnection = (HttpsURLConnection) myurl.openConnection();
httpsURLConnection.setRequestMethod(requestType);
httpsURLConnection.setUseCaches(true);
if (isOnline(parentActivity)) {
httpsURLConnection.addRequestProperty("Cache-Control", "max-age=0");
} else {
httpsURLConnection.setUseCaches(true);
httpsURLConnection.addRequestProperty("Cache-Control", "max-stale=" + CACHE_STALE_TIME_OUT);
httpsURLConnection.addRequestProperty("Cache-Control", "only-if-cached");
}
httpsURLConnection.setConnectTimeout(20 * ONE_SECOND);
httpsURLConnection.setReadTimeout(20 * ONE_SECOND);
httpsURLConnection.setInstanceFollowRedirects(true);
httpsURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
if (sessionId != null) {
httpsURLConnection.setRequestProperty("sessionId", sessionId);
}
httpsURLConnection.setDoInput(true);
if (!requestType.equalsIgnoreCase("GET")) {
Log.v("RequestData", "" + params.toString());
httpsURLConnection.setDoOutput(true);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(httpsURLConnection.getOutputStream(), "UTF-8"));
writer.write(params.toString());
writer.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(writer != null){
try {
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
httpsURLConnection.connect();
} catch (Exception e) {
Log.v("Ex", "1");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
return null;
}
//---------------------READING THE RESPONSE---------------------------//
BufferedReader bReader = null;
try {
final String newSessionId = httpsURLConnection.getHeaderField("sessionId");
final int httpResponseCode = httpsURLConnection.getResponseCode();
Log.v("Req, Response codes", requestCode+", "+httpResponseCode);
if(httpResponseCode == 504 && !LegionUtils.isOnline(parentActivity)){
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
return null;
}
if (httpResponseCode == 401) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
}
});
return null;
} else if ((httpResponseCode == 400 || (httpResponseCode >= 500 && httpResponseCode <= 599)) && !(parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
networkCallback.onFailure(requestCode, null);
}
});
return null;
} else if ((httpResponseCode >= 500 && httpResponseCode <= 599) && (parentActivity instanceof CreateAccountActivity)) {
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, null);
}
});
return null;
}
InputStream inputStream;
try {
inputStream = httpsURLConnection.getInputStream();
}catch (FileNotFoundException e){
e.printStackTrace();
inputStream = httpsURLConnection.getErrorStream();
}
if (inputStream != null) {
bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String inputLine;
final StringBuffer response = new StringBuffer();
while ((inputLine = bReader.readLine()) != null) {
response.append(inputLine);
}
bReader.close();
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.v("RESPONSE " + requestCode, response.toString());
networkCallback.onSuccess(requestCode, response.toString(), newSessionId);
}
});
}
} catch (Exception e) {
Log.v("Ex", "2");
e.printStackTrace();
handleException(requestCode, e, parentActivity);
} finally {
try {
if (bReader != null) {
bReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void handleException(final int requestCode, Exception error, final Activity parentActivity) {
final String errorResponse;
if (error instanceof TimeoutException || error instanceof SocketTimeoutException || error instanceof UnknownHostException) {
errorResponse = "Your request has been timed out. Please try again later.";
} else if (error instanceof SSLException || error instanceof ConnectException) {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
} /*else if (error instanceof FileNotFoundException) {
errorResponse = "Invalid Request.\nPlease try again later.";
} */else if (error instanceof IOException) {
errorResponse = "Something went wrong. Please try again later.";
} else if (error instanceof JSONException) {
errorResponse = "Unexpected response.\nPlease try again later.";
} else {
errorResponse = null;
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
hideProgressDialog();
showOfflineDialog(parentActivity);
}
});
}
Log.v("FAILURE ERR RESPONSE " + requestCode, errorResponse + "");
parentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
networkCallback.onFailure(requestCode, errorResponse);
}
});
}
Here is my code:
public class HttpClient {
public String AddressBase = "";
String _AccessToken = "";
String _AccessToken = "";
public HttpClient() {
}
public HttpClient(String accessToken) {
_AccessToken = accessToken;
}
private HttpURLConnection _CreateConnection(String url, final ArrayList<Pair<String, String>> params) throws IOException {
Uri.Builder uriB1 = Uri.parse(AddressBase).buildUpon()
.appendEncodedPath(url);
if (params != null)
for (Pair<String, String> p :
params) {
uriB1 = uriB1.appendQueryParameter(p.first, p.second);
}
URL callUrl = new URL(uriB1.build().toString());
HttpURLConnection connection = (HttpURLConnection) callUrl.openConnection();
if (!_AccessToken.isEmpty())
connection.setRequestProperty("Authorization", "Bearer " + _AccessToken);
return connection;
}
private <T, Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final T object, final Class<Y> objectClass) {
Log.e("check net", "_post");
return _Post(url, params, AppConstants.Gson_Get().toJson(object), "application/json", objectClass);
}
private <Y> Y _Post(final String url, final ArrayList<Pair<String, String>> params, final String postBodyContent, String postBodyContentType, final Class<Y> objectClass) {
Y r = null;
HttpURLConnection connection = null;
try {
Log.e("tag", " try create connection");
connection = _CreateConnection(url, params);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", postBodyContentType);
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
if (postBodyContent != null && !postBodyContent.isEmpty()) {
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
wr.write(postBodyContent);
wr.flush();
}
connection.connect();
Log.e("tag", " connection connected");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String h1 = connection.getHeaderField("Content-Encoding");
if (h1 != null && h1.equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
private String _ConvertStreamToString(InputStream inputStream) {
Log.e("checknet", "cnovert stram to string");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return stringBuilder.toString();
}
public <T, Y> Y Post(final String url, final T object, final Class<Y> objectClass) {
return _Post(url, null, object, objectClass);
}
public <T> T PostParamsInQuery(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
return _Post(url, params, null, "application/json", objectClass);
}
public <T> T PostParamsInBody(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
StringBuilder postBodyContent = new StringBuilder("");
for (Pair<String, String> p :
params) {
try {
if (postBodyContent.length() != 0)
postBodyContent.append('&');
postBodyContent.append(URLEncoder.encode(p.first, "UTF-8"));
postBodyContent.append("=");
postBodyContent.append(URLEncoder.encode(p.second, "UTF-8"));
} catch (Exception e) {
}
}
return _Post(url, null, postBodyContent.toString(), "application/x-www-form-urlencoded", objectClass);
}
public <T> T Get(String url, final ArrayList<Pair<String, String>> params, final Class<T> objectClass) {
T r = null;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Encoding", "gzip");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
if (connection.getHeaderField("Content-Encoding").equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = _ConvertStreamToString(inputStream);
inputStream.close();
r = AppConstants.Gson_Get().fromJson(resultString, objectClass);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public boolean Delete(String url, final ArrayList<Pair<String, String>> params) {
boolean r = false;
HttpURLConnection connection = null;
try {
connection = _CreateConnection(url, params);
connection.setRequestMethod("DELETE");
connection.setDoInput(true);
connection.connect();
r = connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (connection != null)
connection.disconnect();
return r;
}
public <T, Y> Y InvokeApi(String apiName, final T arg, Class<Y> returnClass) {
return Post(String.format("/api/%s", apiName), arg, returnClass);
}
public <T, Y> void InvokeApiAsync(final String apiName, final T arg, final Class<Y> returnClass, final ActionListener<Y> listener) {
new AsyncTask<Void, Void, Y>() {
#Override
protected Y doInBackground(Void... params) {
return InvokeApi(apiName, arg, returnClass);
}
#Override
protected void onPostExecute(Y result) {
if (listener != null) {
listener.Action(result);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
When I call InvokeApiAsync it takes long time about 3 minutes to get response because of .getoutputstream(). I've been using AsyncTask for parallel connection too.I dont know what to do anymore I will be grateful for any help.
I had this problem before, check your network (perhaps WiFi) proxy on your device that you test your code on!
Android tries to connect to the proxy and if it fails (incorrect proxy or very slow one) it will wait for a long time (default) to get the outputStream.
Either turn the proxy off or set the time out to smaller value to get the timeout exception sooner!
You had better use an IntentService instead of AsyncTask for API connections.
I am trying to send a POST request using Plivo (VoIP server) to send a SMS to my cell phone, but I just receive BAD REQUEST (Request Code 400).
The error I received is "error": "invalid json data sent in raw POST"
I can't find where it's wrong.
Can someone help me?
final AsyncTask<String, Void, Boolean> request = new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... strings) {
Boolean retorno = true;
HttpsURLConnection request = null;
try {
request = (HttpsURLConnection) finalUrl.openConnection();
System.out.println("Define POST");
request.setRequestMethod("POST");
request.setUseCaches(false);
request.setDoOutput(true);
System.out.println("Define propriedades");
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
request.setRequestProperty("Accept-Charset", "UTF-8");
request.setRequestProperty("charset", "UTF-8");
System.out.println("Define autenticação");
String autenticacao = authID + ":" + authToken;
String basic = "Basic " + new String(Base64.encode(autenticacao.getBytes(), Base64.NO_WRAP));
request.setRequestProperty("Authorization", basic);
System.out.println("Define parâmetros");
JSONObject params = new JSONObject();
params.put("dst", numeroDestino);
params.put("src", numeroOrigem);
params.put("text", body);
System.out.println("Faz conexão e requisição");
request.connect();
OutputStreamWriter postParaEnvio = new OutputStreamWriter(request.getOutputStream());
postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8"));
postParaEnvio.flush();
postParaEnvio.close();
int codigoStatus = request.getResponseCode();
for (Map.Entry<String, List<String>> header : request.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
if (codigoStatus == 202) {
System.out.println("OK");
} else {
System.out.println("Falha");
System.out.println(codigoStatus);
retorno = false;
}
} catch (IOException e) {
System.out.println("Falha Exception");
e.printStackTrace();
retorno = false;
} catch (JSONException e) {
e.printStackTrace();
retorno = false;
} finally {
request.disconnect();
}
return retorno;
}
#Override
protected void onPostExecute(Boolean result) {
indicadorDeAtividade.dismiss();
if(result) {
} else {
mostrarErro(0, R.string.erroEnviarCodigo);
}
}
}.execute();
SOLVED
When sending Json object, it must be passed to String but it cannot be coded.
Modifing the line postParaEnvio.write(URLEncoder.encode(params.toString(), "UTF-8")); to postParaEnvio.write(params.toString()); solved the problem.
I Think this may help you.
By the way,
My Dependencies : gradle->
compile 'com.android.support:appcompat-v7:23.4.0'
class BackGround extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String email = params[2];
String phone=params[3];
String data="";
int tmp;
try {
URL url = new URL("http://domain.com/yourFile.php");
String urlParams = "name="+name+"&password="+password+"&email="+email+"&phone="+phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data Saved! Success...";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}
I'm using HttpUrlConnection in my android app. I'm trying to send a post request to a particular url every 2 seconds. Below is the code for the same.
The issue I have is, I get 200 OK response for the first approx 200-250 calls, and after that every call starts failing with 400 Bad requestYour browser sent an invalid request.
I force stop my app, and then as mentioned above the first 200-250 hits to my url comes with 200 OK and then starts failing with 400. I was able to reproduce this consistently every time. I tried almost like 10 times and the same thing happens.
When I tried AndroidHttpClient I was able to make close to like 15000 hits to the same url without a single failure, so definitely not a server issue.
I'm trying to understand what is the issue with httpUrlConnection, as I would like to stick with httpUrlConnection as it is recommended by Google. As far as I see I have done all error handling fine.
I even tried to set http.keepAlive System property to false at the start of my appln/ included connection "Close" header before making the connection but nothing helped.
Could someone help me understand what am I doing wrong here?
HttpURLConnection con = null;
final BufferedReader rd = null;
final BufferedOutputStream wr = null;
final InputStreamReader isr = null;
ServerConnectionData serverConnectionData = null;
try {
serverConnectionData = (ServerConnectionData) connectionData;
final String urlPath = serverConnectionData.getUrlPath();
final URL url = new URL(urlPath);
trust();
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
final URLConnection urlConnection = url.openConnection();
con = (HttpURLConnection) urlConnection;
con.setRequestMethod("POST");
// con.addRequestProperty("Connection", "Keep-Alive");
// con.addRequestProperty("Connection", "Close");
if (serverConnectionData.getJsonData() != null) {
con.addRequestProperty(
"Content-Length",
Integer.toString(serverConnectionData.getJsonData().getBytes(
Charset.forName("UTF8")).length));
}
if (serverConnectionData.getAdditionalHeaders() != null) {
final Map<String, String> additionalHeaders =
serverConnectionData.getAdditionalHeaders();
final Set<String> keySet = additionalHeaders.keySet();
for (final Object key : keySet) {
con.addRequestProperty((String) key, additionalHeaders.get(key));
}
}
final String authToken = "Bearer " + "my outh token";
con.addRequestProperty("Authorization", authToken);
con.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setUseCaches(false);
con.setConnectTimeout(60000);
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
sendData(con, serverConnectionData);
responseCode = con.getResponseCode();
responseText = getResponseText(con);
if (responseCode == 200) {
// success
} else {
// failure }
}
} catch (final MalformedURLException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final IOException e) {
Log.e(e.toString());
try {
if (null != con) {
responseCode = con.getResponseCode();
responseText = getResponseText(con);
}
if (responseCode == 401) {
// handle 401 response
} else {
final ConnectionException ce =
new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
ce.setResponseCode(responseCode);
throw ce;
}
} catch (final UnsupportedEncodingException uee) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
uee.getStackTrace());
} catch (final IOException ioe) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
ioe.getStackTrace());
}
} catch (final KeyManagementException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final NoSuchAlgorithmException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} catch (final Exception e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR, e.getStackTrace());
} finally {
if (wr != null) {
try {
wr.flush();
wr.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (isr != null) {
try {
isr.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (rd != null) {
try {
rd.close();
} catch (final IOException e) {
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
if (con != null) {
con.disconnect();
}
}
private void trust() throws NoSuchAlgorithmException, KeyManagementException {
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkClientTrusted(final java.security.cert.X509Certificate[] certs,
final String authType) {
}
#Override
public void checkServerTrusted(final java.security.cert.X509Certificate[] certs,
final String authType) {
}
}
};
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public void sendData(final HttpURLConnection con, final ServerConnectionData serverConnectionData)
throws IOException, ConnectionException {
final String requestJSON = serverConnectionData.getJsonData();
if (requestJSON != null) {
BufferedOutputStream bufferedOutputStream = null;
try {
bufferedOutputStream = new BufferedOutputStream(con.getOutputStream());
bufferedOutputStream.write(requestJSON.getBytes());
bufferedOutputStream.flush();
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (final IOException e) {
setOnlineStatus(ONLINE_STATUS_BAD);
throw new ConnectionException(ErrorCodes.SERVER_CONNECTION_ERROR,
e.getStackTrace());
}
}
}
}
}
public String getResponseText(final HttpURLConnection con) throws IOException {
InputStream stream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
String responseText = null;
try {
final int responseCode = con.getResponseCode();
if (200 == responseCode) {
stream = con.getInputStream();
}
if (null == stream) {
stream = con.getErrorStream();
}
if (null == stream) {
return "";
}
inputStreamReader = new InputStreamReader(stream, "UTF8");
bufferedReader = new BufferedReader(inputStreamReader);
final StringBuilder sb = new StringBuilder("");
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
responseText = sb.toString();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (stream != null) {
stream.close();
}
}
return responseText;
}
im currently trying to implement the Steam Web API using the given code in the following repository -> https://github.com/Overv/SteamWebAPI/blob/master/SteamAPISession.cs into my Android app and im getting different exceptions dependend on using the given wep api ip ( 63.228.223.110 ) or the adress ( https://api.steampowered.com/ ) itself.
my code actually looks like this in the given method when building up a connection to the web api:
private String steamRequest( String get, String post ) {
final int MAX_RETRIES = 3;
int numberOfTries = 0;
HttpsURLConnection request = null;
while(numberOfTries < MAX_RETRIES) {
if (numberOfTries != 0) {
Log.d(TAG, "Retry -> " + numberOfTries);
}
try {
request = (HttpsURLConnection) new URL("https://api.steampowered.com/" + get).openConnection(); //or 63.228.223.110/ ???
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
String host = "api.steampowered.com";
int port = 443;
int header = 0;
socketFactory.createSocket(new Socket(host, port), host, port, false);
request.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
request.setSSLSocketFactory(socketFactory);
request.setDoOutput(false);
// request.setRequestProperty("Host", "api.steampowered.com:443");
// request.setRequestProperty("Protocol-Version", "httpVersion");
request.setRequestProperty("Accept", "*/*");
request.setRequestProperty("Accept-Encoding", "gzip, deflate");
request.setRequestProperty("Accept-Language", "en-us");
request.setRequestProperty("User-Agent", "Steam 1291812 / iPhone");
request.setRequestProperty("Connection", "close");
if (post != null) {
byte[] postBytes;
try {
request.setRequestMethod("POST");
postBytes = post.getBytes("US-ASCII");
// request.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
request.setFixedLengthStreamingMode(postBytes.length);
request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(request.getOutputStream());
out.print(post);
out.close();
// DataOutputStream requestStream = new DataOutputStream(request.getOutputStream());
//// OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream());
//// stream.write(postBytes, 0, postBytes.length);
// requestStream.write(postBytes, 0, postBytes.length);
// requestStream.close();
message++;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
int statusCode = request.getResponseCode();
InputStream is;
Log.d(TAG, "The response code of the status code is" + statusCode);
if (statusCode != 200) {
is = request.getErrorStream();
Log.d(TAG, String.valueOf(is));
}
// String src = null;
// OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
// out.write(src);
// out.close();
Scanner inStream = new Scanner(request.getInputStream());
String response = "";
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
// String src;
// BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
// StringBuilder builder = new StringBuilder();
// while ((src = in.readLine()) != null) {
// builder.append(src);
// }
// String jsonData = builder.toString();
Log.d(TAG, response); //jsonData
// in.close();
return response; //jsonData
} catch (MalformedURLException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.disconnect();
}
}
numberOfTries++;
}
Log.d(TAG, "Max retries reached. Giving up on connecting to Steam Web API...");
return null;
}
following exception occurs when using https://api.steampowered.com/ as url:
W/System.err﹕ java.io.FileNotFoundException: https://api.steampowered.com/ISteamOAuth2/GetTokenWithCredentials/v0001
D/OptionsFragment﹕ Failed to log in!
i've really tried and researched on those issues, but i just can't get a solution. If someone got a good hint on helping to solve these exceptions please let me know!
EDIT:
I've researched some more!
Looking up on https://partner.steamgames.com/documentation/webapi#creating the direct ip adress shouldn't be used and therefore only the DNS name itself (for further clarification look on the given link). Hence, looking up on the API interface list itself -> http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?format=json there doesn't seem to be a given Interface with a method called ISteamOAuth2/GetTokenWithCredentials.(Or not anymore!) Only ISteamUserAuth and ISteamUserOAuth which seem to handle Authentication stuff.
I will update this post again if i should get a working connection and handling with the steam web api.
Cheers!