Download image with json data (retrofit2 android) - java

I want download image but url image is not direct and should send additional data like that :
url : http://example.com/download
data :
{
"phoneNumber":"9199191",
"token":"1KAwqCxCdQUjTvTK9EtT7N",
"fileName":"632_macbook_pro.jpg"
}
and server callback data image In the form of base64
i use this codes but server return 500 code :
restservice :
#POST("download")
Call<ResponseBody> getImage(
#Body JsonObject data,
#HeaderMap Map<String, String> headers
);
Java code:
JsonObject params = new JsonObject();
params.addProperty("phoneNumber",settingMain.getPhoneNum());
params.addProperty("token",settingMain.getSecureLogin());
params.addProperty("fileName",fileName);
Call<ResponseBody> myCall = restService.getImage(params, UrlController.AddHeadersDownload(fileName));
myCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj) {
try {
Log.e("DownloadCode",responseObj.code()+"");
if (responseObj.isSuccessful() && responseObj.code()==200) {
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSONException",e.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});

This is a little example showing how to download the Retrofit JAR file. You can adapt it to your needs.
This is the interface:
import com.squareup.okhttp.ResponseBody;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
interface RetrofitDownload {
#GET("/maven2/com/squareup/retrofit/retrofit/2.0.0-beta2/{fileName}")
Call<ResponseBody> downloadRetrofit(#Path("fileName") String fileName);
}
And this is a Java class using the interface:
import com.google.common.io.Files;
import com.squareup.okhttp.ResponseBody;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String... args) {
Retrofit retrofit = new Retrofit.Builder().
baseUrl("http://repo1.maven.org").
build();
RetrofitDownload retrofitDownload = retrofit.create(RetrofitDownload.class);
Call<ResponseBody> call = retrofitDownload.downloadRetrofit("retrofit-2.0.0-beta2.jar");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofitParam) {
File file = new File("retrofit-2.0.0-beta2.jar");
try {
file.createNewFile();
Files.asByteSink(file).write(response.body().bytes());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
}

Related

Java Websocket closes immediately

I am trying to use TooTallNate's Java-Websocket to connect to OkCoin. I found this simple code example somewhere, but I can't get it to work. The connection is immediately closed and so the call mWs.send(...) throws a WebsocketNotConnectedException. I can't figure out why; so far I have found a number of similar questions, none of which have an answer.
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
try {
URI uri = new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi");
final WebSocketClient mWs = new WebSocketClient(uri) {
#Override
public void onMessage(String message) {
JSONObject obj = new JSONObject(message);
}
#Override
public void onOpen(ServerHandshake handshake) {
System.out.println("opened connection");
}
#Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("closed connection");
}
#Override
public void onError(Exception ex) {
ex.printStackTrace();
}
};
mWs.connect();
JSONObject obj = new JSONObject();
obj.put("event", "addChannel");
obj.put("channel", "ok_btccny_ticker");
mWs.send(obj.toString());
} catch (URISyntaxException e) {
System.err.println("URI not formatted correctly");
}
}
}
Use mWs.connectBlocking() instead of mWs.connect() with this it will not close automatically.
See

Character encoding in com.sun.net.httpserver

I'm trying to write a mock HTTP server for unit tests, I'm using the com.sun.net.httpserver classes for that.
I'm having problem with the encoding of the URL: the query parameters are ISO-8859-1 encoded, but the URI that is passed to the handler (via HttpExchange) is not.
As I can't change the encoding of the original server, I was wondering if there was a way to tell the HttpServer which encoding to use when decoding the URL.
Thanks in advance.
Here is a test program:
package test34;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
try {
MockServer mock = new MockServer();
mock.start(8642);
URL url = new URL("http://localhost:8642/?p="
+ URLEncoder.encode("téléphone", "ISO-8859-1"));
System.out.println(url);
InputStream in = url.openStream();
while (in.read() > 0) {
}
in.close();
mock.stop();
System.out.println(mock.getLastParams().get("p"));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And here is the code of the mock server:
package test34;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class MockServer {
private HttpServer httpServer;
private Map<String, String> params;
public void start(int port) {
if (httpServer == null) {
try {
InetSocketAddress addr = new InetSocketAddress(port);
httpServer = HttpServer.create(addr, 0);
httpServer.createContext("/", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
try {
handleRoot(exchange);
} catch (RuntimeException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
});
httpServer.setExecutor(Executors.newFixedThreadPool(1));
httpServer.start();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
public void stop() {
if (httpServer != null) {
httpServer.stop(10);
httpServer = null;
}
}
public Map<String, String> getLastParams() {
Map<String, String> result = new HashMap<String, String>();
if (params != null) {
result.putAll(params);
}
return result;
}
private void handleRoot(HttpExchange exchange) throws IOException {
URI uri = exchange.getRequestURI();
params = parseQuery(uri.getQuery());
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain;charset=ISO-8859-1");
exchange.sendResponseHeaders(200, 0);
OutputStream stream = exchange.getResponseBody();
try {
Writer writer = new OutputStreamWriter(stream, "ISO-8859-1");
try {
PrintWriter out = new PrintWriter(writer);
try {
out.println("OK");
} finally {
out.close();
}
} finally {
writer.close();
}
} finally {
stream.close();
}
}
private static Map<String, String> parseQuery(String qry)
throws IOException {
Map<String, String> result = new HashMap<String, String>();
if (qry != null) {
String defs[] = qry.split("[&]");
for (String def : defs) {
int ix = def.indexOf('=');
if (ix < 0) {
result.put(def, "");
} else {
String name = def.substring(0, ix);
String value = URLDecoder.decode(
def.substring(ix + 1), "ISO-8859-1");
result.put(name, value);
}
}
}
return result;
}
}
The javadoc of HttpExchange.getQueryString() says it returns "undecoded query string of request URI, or null if the request URI doesn't have one."
If it's not decoded, and since http headers have to be in 7 bit ASCII (ietf.org/rfc/rfc2616.txt) , then you can decode later with URLDecoder.decode(... "ISO-8859-1");

get XML from server by URL in AsyncTask and return response to UI

I try to get xml from server in async task, but my doInBackground method returns me NULL. Where is my mistake? And how I can send result to UI?
Here is all classes
I have this code for getting xml from server:
package classes;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by Mikhail on 28.03.2015.
*/
public class GetXMLFromServer {
InputStreamReader reader;
public GetXMLFromServer(){
//reader = null;
}
public InputStreamReader getReaderWithXML(String url){
GetXMlTask task = new GetXMlTask();
task.execute(url);
return reader;
}
public void setReader(InputStreamReader newReader){
this.reader = newReader;
}
class GetXMlTask extends AsyncTask<String, Integer, InputStreamReader>{
#Override
protected InputStreamReader doInBackground(String... params) {
InputStreamReader iStream = null;
try {
iStream = new InputStreamReader(getUrlData(params[0]));
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return iStream;
}
#Override
protected void onPostExecute(InputStreamReader inputStreamReader) {
super.onPostExecute(inputStreamReader);
setReader(inputStreamReader);
}
public InputStream getUrlData(String urlString) throws URISyntaxException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(String.valueOf(new URL(urlString)));
HttpResponse res = client.execute(method);
StatusLine status = res.getStatusLine();
if (status.getStatusCode() != 200) {
Log.d("APP", "HTTP error.Invalid server status code: " + res.getStatusLine());
}
return res.getEntity().getContent();
}
}
}
You have a good example how to use async task here.
Please check it!
The returning is in onPostExecute method.
To send the result to UI use OnPostExecute do call a static method of your UI class.
protected void onPostExecute(Long result) {
YourUIFragmentORActivity.showResult(result);
showDialog("Downloaded " + result + " bytes");
}

Passing data (other than payload) via websockets

Once the websocket session has been established, is it possible to pass data other than using session.getAsyncRemote().sendText(**)) across the session?
I am using
javax.websocket.* as ClientEndpoint
and spring-websocket for server.
I have tried using:
session.getRequestParameterMap().putAll(bMap); //This gives me exception
session.getPathParameters().putAll(aMap); //This gives me exception
session.getUserProperties().put("dataE", "dataF");; //This goes through fine
And I am not able to see the data on server side:
Map<String, Object> aMap = stStandard.getNativeSession().getUserProperties();
This map comes as blank on server side.Please let me know if more information is needed. Here is my code:
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
#ClientEndpoint
public class TestSpring {
#OnMessage
public void onMessage(String message, Session session) throws IOException,
InterruptedException {
Map aMap = new HashMap();
aMap.put("dataA", "dataB");
try {
session.getPathParameters().putAll(aMap);
} catch (Exception e) {
e.printStackTrace();
}
Map bMap = new HashMap();
List<String> bList = new ArrayList<String>();
bList.add("dataC");
try {
bMap.put("dataD", bList);
session.getRequestParameterMap().putAll(bMap);
} catch (Exception e) {
e.printStackTrace();
}
try {
session.getUserProperties().put("dataE", "dataF");
} catch (Exception e) {
e.printStackTrace();
}
session.getAsyncRemote().sendText("Data to be sent");
}
#OnOpen
public void onOpen() {
System.out.println("Client connected");
}
#OnClose
public void onClose() {
System.out.println("Connection closed");
}
}
import java.util.List;
import java.util.Map;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketExtension;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import com.sap.websocket.inMemoryWebSockets.KeepInMemoryWebSockets;
public class WebsocketEndPoint extends AbstractWebSocketHandler {
#Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
session.getHandshakeHeaders();
StandardWebSocketSession stStandard = (StandardWebSocketSession) session;
try {
Map<String, Object> aMap = stStandard.getNativeSession()
.getUserProperties();
} catch (Exception e) {
e.printStackTrace();
}
TextMessage binaryMessage = new TextMessage(new String(
"Hello Client. This is message sent from server"));
session.sendMessage(binaryMessage);
}
#Override
protected void handleBinaryMessage(WebSocketSession session,
BinaryMessage message) throws Exception {
}
}

Web Socket in Tomcat 7

I am new in web socket. I had learned some tutorial to implement web socket. But it is not working properly. I don't know what I have done wrongly.
note: I have not done any configuration (web.xml) and I have been used tomcat 7.0.47,jdk 1.6.0_24
This is My Server side code:
package com.hmkcode;
import java.io.IOException;
import java.util.LinkedList;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value="/websocket/{client-id}")
public class MyServerEndpoint {
private static final LinkedList<Session> clients = new LinkedList<Session>();
#OnOpen
public void onOpen(Session session) {
clients.add(session);
}
#OnMessage
public void onMessage(String message,#PathParam("client-id") String clientId) {
for (Session client : clients) {
try {
client.getBasicRemote().sendObject(clientId+": "+message);
} catch (IOException e) {
e.printStackTrace();
} catch (EncodeException e) {
e.printStackTrace();
}
}
}
#OnClose
public void onClose(Session peer) {
clients.remove(peer);
}
}
This is my Web client code
var URL = "ws://localhost:8080/WebSocket1/websocket/web-client";
var websocket;
$(document).ready(function(){
connect();
});
function connect(){
websocket = new WebSocket(URL);
websocket.onopen = function(evnt) { onOpen(evnt);};
websocket.onmessage = function(evnt) { onMessage(evnt); };
websocket.onerror = function(evnt) { onError(evnt); };
}
function sendMessage() {
websocket.send($("#message").val());
}
function onOpen() {
updateStatus("connected");
}
function onMessage(evnt) {
if (typeof evnt.data == "string") {
$("#received_messages").append(
$('<tr/>')
.append($('<td/>').text("1"))
.append($('<td/>').text(evnt.data.substring(0,evnt.data.indexOf(":"))))
.append($('<td/>').text(evnt.data.substring(evnt.data.indexOf(":")+1))));
}
}
function onError(evnt) {
alert('ERROR: ' + evnt.data);
}
function updateStatus(status){
if(status == "connected"){
$("#status").removeClass (function (index, css) {
return (css.match (/\blabel-\S+/g) || []).join(' ');
});
$("#status").text(status).addClass("label-success");
}
}
My guess is...
Since you ServerEndpoint maps an argument "{client-id}" it should be present in the URL your client uses to connect.
Either you remove the parameter on server-side or you need to include a value to it on client-side.
Again, just guessing. It would be useful if you include more information regarding the issue (e.g., server logs)
[]s
Heleno

Categories