how to upload file into server in android? - java

How do i send a file(data) from a mobile device to server using volley library.
here i have listed my param below please help me to solve this.
Map<String, String> mHeaderPart= new HashMap<>();
mHeaderPart.put("Content-type", "multipart/form-data;");
mHeaderPart.put("Authorization", authorizationKey);
//String part
Map<String, String> mStringPart= new HashMap<>();
mStringPart.put("candidate_id", SessionStores.getBullHornId(getActivity()));
mStringPart.put("externalID", "portpolio");
mStringPart.put("fileCount", "2");//number of files
mStringPart.put("fileType", "SAMPLE");
mStringPart.put("platform", "android");
//file param
Map<String, File> mFilePartData= new HashMap<>();
In above file param i have to add n number of files and sent it to the server. How do i get file from device and add n number of files with param and sent it to the server if anyone could you please give me suggestion.
And if anyone have example of sending multiple files with param using volley please guide me. Thanks in advance.

Volly don't provide direct way to upload file on server using multi part.
For uploading multiple files using volly follow below steps:
Step 1: Create a new Class named MultipartRequest.java that extends Request from volly like below:
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MultipartRequest extends Request<String> { private MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); HttpEntity entity;
private HashMap<String, File> sendFile = new HashMap<>();
/**
*
* #param url url
* #param errorListener volly error listenere
* #param sendFile HashMap with key as file name and value as file object
*/
public MultipartRequest(String url, Response.ErrorListener errorListener, HashMap<String, File> sendFile) {
super(Method.POST, url, errorListener);
this.sendFile = sendFile;
buildMultipartEntity();
entity = entitybuilder.build();
}
private void buildMultipartEntity() {
if (sendFile != null)
for (Map.Entry<String, File> entry : sendFile.entrySet()) {
entitybuilder.addPart(entry.getKey(), new FileBody(entry.getValue()));
// here you can set key as filename
// value will be the file object to be upload
}
}
#Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
try {
String json = new String(
networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
return Response.success(json, HttpHeaderParser.parseCacheHeaders(networkResponse));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(String s) {
//Your response
}
}
step 2:
From your activity:
public void executeMultipart(String url,HashMap<String, File> fileData) {
try { MultipartRequest mRequest = new MultipartRequest(url , new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError volleyError) {
}
},fileData);
mRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
} catch (Exception e) {
e.printStackTrace();
}
}
step 3: In your app build.gradle file add:
compile('org.apache.httpcomponents:httpmime:4.3.6') { exclude module: 'httpclient' }
Note: From API 22 org.apache.http.HttpEntity is deprecated , so better to use either URLConnection or you can use retrofit library both have thier own advantages and disadvantages

Related

How can i pass data from class to another class?

I am doing in this code: message receiving,filtering and getting then sending data to a sql server. I need the category_id from mysql database. Then i will use it in CallAPI as ide . I took the data from my mysql database but i couldn't transfer the data one class to another. So how can i transfer the data from one class to another?
I solved my problem and updated it i hope it can help to another peoples.
my smsCame codes:
package com.pvalid.api;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;
public class smsCame extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG , "SMS RECEIVEDD");
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
String format = intent.getExtras().getString("format");
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0], format);
String messagea = message.getOriginatingAddress();
String messagesb = message.getMessageBody();
Boolean messagee= messagesb.substring(0, 8).matches("(G-)\\d\\d\\d\\d\\d\\d");
String Code = messagesb.substring(2, 8);
String ide;
String usercode = "Admin";
//i need to POST this lmessage to my php server when sms received
//property is has to be Code:lmessage
// i have a receiver in my url when isset($_POST['Code'])
if (messagee){
try{
ide = new heyAPI(usercode).execute().get();
new CallAPI(usercode, Code, ide).execute();}
catch(Exception e){
ide="11";
new CallAPI(usercode, Code, ide).execute();
}
}
else{
Log.i(TAG,"Didnt match");}
}
private static class heyAPI extends AsyncTask<String, String, String> {
private final OkHttpClient client = new OkHttpClient();
String usercodes;
private heyAPI(String usercode){
usercodes= usercode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
RequestBody formBody = new FormBody.Builder()
.add("usercode", usercodes) // A sample POST field
.build();
Request request = new Request.Builder()
.url("url-here")
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
String elem_id= response.body().string();
return elem_id;
}
catch (Exception e){
Log.i(TAG,"Error:"+e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
private static class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
String id;
private CallAPI(String usercode, String Code,String ide){
emailString = usercode;
commentString = Code;
id=ide;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("usercode", emailString) // A sample POST field
.add("Code", commentString) // Another sample POST field
.add("category_id", id) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("url here") // The URL to send the data to
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
}catch(IOException e){
Log.i(TAG,"IO exception");
return "";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
You can use transfer your data in different class by using database , shared preference and intents.
If You want to transfer data from class A to B by intent then
In class A
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("key_name", value);
startActivity(intent);
and In class B for getting the transferred data
Intent intent=new getIntent();
String s=intent.getExtras().getString("key_name");
hi you can send parameters class A to class B is so way...
you can use constructor like this
public class test {
public test(String p){...}
}
and you can use intent
you can use shared preference in
learn with this site Shared preference
save data from class A and read class B
and you must be careful because when you give data from server thread is different Ui thread !
private SharedPreferences mPreference;
mPreference = getSharedPreferences("Share", Context.MODE_PRIVATE);
// save data
mPreference.edit()
.putBoolean("test", category_id)
.apply();
// read data
mPreference.getString("test", defaultSTR);

Carrying and reusing information (json string) from an AsyncTask?

I have created a simple android app with 3 TextViews and then run an AsyncTask Task via a different class the next step would be to carry the information over and make the task reusable.
The Task will consume a String (URL) and the context of the MainActivity.
The Task will make a simple REST Request (GET) and retrieve a json string.
I have then created another class that which gets the json response and creates a .json file saves it to
..../0/Notes/launch.json
The folder "Notes is created by myself via file.mkdirs().
In the MainActivity I created an InputStream to read the .json file saved by the AsyncTask but once I try to open it, it gives me a FileNotFoundException.
Here's the code of my MainActivity.class
package com.example.root.example;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
String url = "https://api.spacexdata.com/v3/launches/upcoming"; //Copy the url and open it in your browser to see the json.
AsyncCall asyncCall = new AsyncCall(getApplicationContext());
asyncCall.myAsyncTask(url);
try {
InputStream inputStream = this.getAssets().open("launch.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String jsonStringFromFile= new String(buffer,"UTF-8");
JSONObject launchObject = new JSONObject(jsonStringFromFile);
System.out.println(launchObject.get("flight_number"));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the AsyncCall.class (making and retrieving the json etc..)
package com.example.root.example;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class AsyncCall {
FileCreator fileCreator = new FileCreator();
private final Context myContext;
public AsyncCall(final Context context) {
myContext = context;
}
public void myAsyncTask(final String url) {
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
fileCreator.generateFile(myContext, myContext.getString(R.string.fileName), response.body().string());
} catch (IOException ioe) {
ioe.getMessage();
}
return null;
}
}.execute();
}
}
what am I trying to archive? I'm trying to save information (json here) and make it reusable just as the Falcon 9.
The issue lies in carrying information over to a different class.
If there's an alternative solution (other than saving a .json file) to fix this issue then please don't hesitate to post it.
This is just my first issue, the second issue appears once you open the api link and see that there are a few more than just one JSON String (0,1,2,3,4... upcoming missions).
I have no clue in any way to tacle the first let alone the second problem and have started over a few times, a while ago multiple times.
Within your Activity, you can get the JSON like so
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, final Response response) throws IOException {
try {
final String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
String flightNumber = json.getString("flight_number");
// TODO: Load number into a TextView
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Looking at your API response, though, you'll actually need new JSONArray(responseData), and you would have to loop over that to get each individual object's flight number

500 Error - Uploading An Audio File Using AcrCloud RESTful api

I upload an audio file to an audio & video bucket, called demo, using the AcrCloud RESTful services. I am getting a 500 Internal Server Error. This indicates that my signature is correct (I was getting a 422 when the signature was incorrect). The part that I suspect is incorrect is the construction of the multipart post request
My Code:
import com.xperiel.common.logging.Loggers;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.MultipartContent;
import com.google.api.client.http.MultipartContent.Part;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CharStreams;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class TestAcrCloudSignature {
private static final String ACCESS_KEY = "xxxx"; // confidential
private static final String SECRET_KEY = "yyyy"; // confidential
private static final String URL = "https://api.acrcloud.com/v1/audios";
private static HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
private static final Logger logger = Loggers.getLogger();
public static void main(String [] args) {
String filePath = "/Users/serena/Desktop/ArcCloudMusic/Fernando.m4a";
String httpMethod = HttpMethod.POST.toString();
String httpUri = "/v1/audios";
String signatureVersion = "1";
long timestamp = System.currentTimeMillis();
String stringToSign = getStringToSign(httpMethod, httpUri, signatureVersion, timestamp);
String signature = getSignature(stringToSign);
logger.log(Level.INFO, "Timestamp:\t" + timestamp);
HttpResponse response = null;
try {
ImmutableMap<String, String> params = ImmutableMap.of(
"title", "fernando",
"audio_id", "1",
"bucket_name", "demo",
"data_type", "audio");
byte[] audio = getAudioFileTo(filePath);
String strResponse = sendMultiPartPostRequest(
"",
params,
ImmutableMap.of("audio-file", new Pair<>("Fernando.m4a", audio)),
signatureVersion,
signature,
timestamp);
logger.log(Level.INFO, "RESPONSE:" + strResponse);
} catch (Exception e) {
logger.log(Level.WARNING, "Response: " + response);
logger.log(Level.WARNING, "Exception: " + e.getMessage());
e.printStackTrace();
}
}
private static String getStringToSign(String method, String httpUri, String signatureVersion, long timestamp) {
String stringToSign = method+"\n"+httpUri+"\n"+ACCESS_KEY+"\n"+signatureVersion+"\n"+timestamp;
logger.log(Level.INFO, "String to Sign:\t" + stringToSign);
return stringToSign;
}
private static String getSignature(String stringToSign) {
String signature = BaseEncoding.base64().encode(hmacSha1(stringToSign));
logger.log(Level.INFO, "Signature:\t" + signature);
return signature;
}
private static byte[] hmacSha1(String toSign) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA1"));
return mac.doFinal(toSign.getBytes());
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
}
private enum HttpMethod {
GET, POST, PUT, DELETE,
}
private static byte[] getAudioFileTo(String filePath){
File file = new File(filePath);
byte[] buffer = null;
try {
InputStream fis = new FileInputStream(file);
buffer = new byte[(int) file.length()];
fis.read(buffer, 0, buffer.length);
fis.close();
} catch (IOException e) {
logger.log(Level.WARNING, "IOException: " + e.getMessage());
}
return buffer;
}
private static String sendMultiPartPostRequest(
String path,
ImmutableMap<String, String> parameters,
ImmutableMap<String, Pair<String, byte[]>> blobData,
String signatureVersion,
String signature,
long timestamp) {
try {
MultipartContent multipartContent = new MultipartContent();
multipartContent.setMediaType(new HttpMediaType("multipart/form-data"));
multipartContent.setBoundary("--------------------------0e94e468d6023641");
for (Entry<String, String> currentParameter : parameters.entrySet()) {
HttpHeaders headers = new HttpHeaders();
headers.clear();
headers.setAcceptEncoding(null);
headers.set("Content-Disposition", "form-data; name=\"" + currentParameter.getKey() + '\"');
HttpContent content = new ByteArrayContent(null, currentParameter.getValue().getBytes());
Part part = new Part(content);
part.setHeaders(headers);
multipartContent.addPart(part);
}
for (Entry<String, Pair<String, byte[]>> current : blobData.entrySet()) {
ByteArrayContent currentContent = new ByteArrayContent("application/octet-stream", current.getValue().second);
HttpHeaders headers = new HttpHeaders();
headers.clear();
headers.setAcceptEncoding(null);
headers.set("Content-Disposition", "form-data; name=\"" + current.getKey() + "\"; filename=\"" + current.getValue().first + '\"');
headers.setContentType("application/octet-stream");
multipartContent.addPart(new Part(headers, currentContent));
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
multipartContent.writeTo(out);
HttpResponse response = requestFactory
.buildPostRequest(new GenericUrl(URL + path), multipartContent)
.setHeaders(new HttpHeaders()
.set("access-key", ACCESS_KEY)
.set("signature-version", signatureVersion)
.set("signature", signature)
.set("timestamp", timestamp))
.execute();
String responseString = CharStreams.toString(new InputStreamReader(response.getContent()));
return responseString;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static class Pair<A, B> {
final A first;
final B second;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
}
}
The error message I am getting from AcrCloud is:
500
{"name":"Internal Server Error","message":"There was an error at the server.","code":0,"status":500}
I am able to upload an audio file using this cUrl command:
Command: $ curl -H "access-key: xxxx" -H "signature-version: 1" -H
"timestamp: 1439958502089" -H "signature:
Nom6oajEzon260F2WzLpK3PE9e0=" -F "title=fernando" -F "audio_id=100" -F
"bucket_name=demo" -F "data_type=audio" -F
"audio_file=#/Users/serena/Desktop/ArcCloudMusic/Fernando.m4a"
https://api.acrcloud.com/v1/audios
Does anyone have any tips on how to debug this? Or has anyone had success using this service programmatically with Java? Or can someone show me how to print the contents of the HttpPOST request?
UPDATE I have also tried using their java example on GITHUB found here:
https://github.com/acrcloud/webapi_example/blob/master/RESTful%20service/UploadAudios.java
I get the same 500 error
UPDATE I no longer get the 500 error when I run their code. I fiddled with the apache jar versions and now I can successfully use the java code found on git hub. For record, The version that I used that work with their github code is apache-http-codec-1.10, apache-http-client-4.5, apache-http-core-4.4.1, apache-http-mime-4.5. When i used apache-http-core-4.5 it did not work.
UPDATE I have written a file that prints out the signatures generated by the java code on github reference above, and my own code. The signatures match so I am convinced that issue in the way I am constructing the multipart post request. I have also written the contents of both post requests to file and the headers contain different information in a few spots.
Thanks Serena for your patience, our team is doing a detailed analysis on the code and the apache jars now. Hopefully will have an update soon.
For now, if anyone who has the same problems, please use the following jars as mentioned in https://github.com/acrcloud/webapi_example/blob/master/RESTful%20service/UploadAudios.java
// import commons-codec-<version>.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi
import org.apache.commons.codec.binary.Base64;
// import HttpClient, download from http://hc.apache.org/downloads.cgi
/**
*
* commons-codec-1.1*.jar
* commons-logging-1.*.jar
* httpclient-4.*.jar
* httpcore-4.4.1.jar
* httpmime-4.*.jar
*
* */

Communication Java-Javascript with http requests

Lately i have been trying to make communication between minecraft server (running with Java) and scratch (running with JavaScript).
I have written the code in java already:
package me.yotam180;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpProcessor {
public MainClass plugin;
public HttpProcessor (MainClass plug) throws IOException {
plugin = plug;
plugin.getLogger().info("CREATED HTTTP PROCESSOR");
HttpServer server = HttpServer.create(new InetSocketAddress(9090), 0);
server.createContext("/pollplayer", new PollPlayerHandler());
server.createContext("/killplayer", new KillPlayerHandler());
plugin.getLogger().info("STARTED HTTTP SERVER");
server.setExecutor(null); // creates a default executor
server.start();
}
static class PollPlayerHandler implements HttpHandler {
#SuppressWarnings("deprecation")
#Override
public void handle(HttpExchange httpExchange) throws IOException {
// TODO Auto-generated method stub
Map <String,String>parms = HttpProcessor.queryToMap(httpExchange.getRequestURI().getQuery());
StringBuilder response = new StringBuilder();
response.append(Bukkit.getPlayer(parms.get("name")).getLocation().toString());
HttpProcessor.writeResponse(httpExchange, response.toString());
}
}
static class KillPlayerHandler implements HttpHandler {
#SuppressWarnings("deprecation")
#Override
public void handle(HttpExchange httpExchange) throws IOException {
// TODO Auto-generated method stub
Map <String,String>parms = HttpProcessor.queryToMap(httpExchange.getRequestURI().getQuery());
Bukkit.getPlayer(parms.get("name")).setHealth(0);
HttpProcessor.writeResponse(httpExchange, "SUCCESS");
}
}
public static void writeResponse(HttpExchange httpExchange, String response) throws IOException {
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
public static Map<String, String> queryToMap(String query){
Map<String, String> result = new HashMap<String, String>();
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length>1) {
result.put(pair[0], pair[1]);
}else{
result.put(pair[0], "");
}
}
return result;
}
}
Now I have to make the scratch side HTTP Client. Every way i tried, It just didn't work. I try to open my browser, i write http://localhost:9090/pollplayer?name=yotam_salmon and it reports my player location beautifully. Now my problmem is the scratch JS.
Here it is:
new (function () {
var ext = this;
// Cleanup function when the extension is unloaded
ext._shutdown = function () { };
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function () {
return { status: 2, msg: 'Ready' };
};
ext.get_Player = function (name, callback) {
//in this function i need to call http://localhost:9090/pollplayer?name= + name, wait for the response and then callback it.
//the response can't be "return response;", and it cannot be call backed from another function. If this function was called, it
//has to report the location back as a string
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['R', 'location of %s', 'get_Player', 'Player'],
]
};
// Register the extension
ScratchExtensions.register('ScratchCraft', descriptor, ext);
})();
I cannot format my JS code differently, because Scratch works only with this format.(It is explained here: http://llk.github.io/scratch-extension-docs/). In the ext.get_Player function i have to go to the Java http server, request /pollplayer?name= + name, and callback it .
I would be happy to get a solution :) Thanks!
The solution was very simple. I just had to add an header of "Allow-Access-Cross-Origin", and it was solved.
httpExchange.getResponseHeaders().set("Access-Control-Allow-Origin", "*");
httpExchange.getResponseHeaders().set("Content-Type", "text/plain");

Android calling page that returns JSON error [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I have a aspx page that I am calling from my android app that is returning JSON text but the java code below breaks here BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
with this error.
error android.os.NetworkOnMainThreadException
ARe you able to help plesae? Thanks
default.aspx return json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/plain";
//Write the message
Response.Write("{'testvar':'testtext'}");
//End the response causing it to be sent
Response.End();
}
}
android java
public void connectWCF() {
try {
URL json = new URL("http://localhost:50851/Default.aspx");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
reader.close();
} catch(Exception e){
}
links where I got the code ideas from
http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/
http://matijabozicevic.com/blog/android-development/android-with-wcf-service
You are placing network communication on the main thread. You should use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
here's a nice video that explains JSON Parsing using AsyncTask.
http://www.youtube.com/watch?v=qcotbMLjlA4
For testing ONLY you can add the following in your Main Activity but it is consider bad practice.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Since android 3.0, you can't put any calls to webpages or similar external resources in the main thread (in other words, any part of the activity) unless you do it with an AsyncTask, in order to avoid apps to look "locked" and unresponsive when waiting for a response from an external datasource. Therefore, you'll need to implement the webservice call with and AsyncTask.
Example class for AsyncTask:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class cargaDatosRest extends AsyncTask<Context, Void, Void> {
private Context c;
private boolean resul = false;
private String control = "";
private String respStrS = "";
public cargaDatosRest(Context C)
{
c = C;
}
public String getStr()
{
return respStrS;
}
public String getControl()
{
return control;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//mProgressDialog.show();
}
#Override
protected Void doInBackground(Context... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("url");
HttpResponse resp;
get.setHeader("content-type", "application/json");
try
{
/*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/
resp = httpClient.execute(getUsuarios);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
this.resul = true;
}
catch(Exception ex)
{
Log.e("ServicioRest","Error!", ex);
this.resul = false;
}
}
public boolean getResul()
{
return this.resul;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
//mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void unused) {
//mProgressDialog.dismiss();
}
}
//calling the AsyncTask from the activity:
CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext());
CallRest.execute();
Log.v("WebService", "Just trying "+arest.getResul());

Categories