Java Multipart File upload with JSON - java

I am developing the Google Drive API using the Restful API.
I need to upload a file and json body.
But when I try to upload with my java code, I was met error code from google-drive.
==> Invalid multipart request with 0 mime parts
Here is the Google-Drive's guide.
enter image description here
And Here is my code.
What is wrong in my code?
public int uploadFileToGoogleDrive(File file, Long acctId, String
accessToken, JSONObject json) {
HttpClient httpClient = new HttpClient();
PostMethod method = null;
Integer result = -1;
String boundary = "---------------------------" + System.currentTimeMillis();
try {
method = new PostMethod("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
method.setRequestHeader("Authorization", "Bearer " + accessToken);
method.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary );
Part[] parts = {new StringPart("",json.toString(),"utf-8"), new FilePart(file.getName(), file, null, "utf-8")};
//MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
httpClient.getHttpConnectionManager().closeIdleConnections(0);
result = httpClient.executeMethod(method);
if (result == HttpStatus.SC_OK) {
InputStream rstream = null;
rstream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(rstream));
String line;
while ((line = br.readLine()) != null) {
resultString += line;
}
}
System.out.println("##############################################\n" + json.toString() + "\n##############################################");
logger.debug(resultString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (ProtocolException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}
catch (IOException e) {
// TODO Auto-generated catch block
logger.error(e.getMessage(), e);
}finally {
method.releaseConnection();
}
return result;
}
}

multipart form uploads work just fine. Just don't specify a custom
Content-Type. Your content-type is going to fail otherwise because the
form-data boundary is determined by the XHR library internally. If you
want to use your Content-Type, then you will have to construct your
request separately and paste it as text in the "Raw" mode
look at this discussioin
and this one

Related

URLEncoder limits the response of the server

I have the following problem..
when I hardcoded a url query which is like
example :
https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gslimit=5&gsradius=10000&gscoord=51.4451254|5.4731413&format=json
(check the link in your browser)
and I make the request to the server, I get the whole response in a string..
However when I make it dynamically I have to pass the "|" character, in URLEncoder.encode("|", "UTF-8") this format...
In that case, the response is only one element of what I want..
Is it something that it is missing to me?
Thanks in advance
protected String doInBackground(String... query) {
String response = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = null;
// try {
HttpResponse execute = null;
try {
//String searchTerm = URLEncoder.encode(query[0], "UTF-8");
httpGet = new HttpGet(query[0]);
execute = client.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = execute.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buffer = new BufferedReader(new InputStreamReader(
content));
String s = "";
try {
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
The above part is my code.. the input query[0] is the url that I am requesting and it is similar to the link that I posted in the beginning.
If I hardcoded the url (set directly the the link), I have the response. My response is a string in json format. (for now I let it string)
If I make the query dynamically, for example like:
gsQuery = mainPage + "&gsradius=" + radius + "&gscoord=" + latitude + URLEncoder.encode("|", "UTF-8") + longtitude +"&format=json";
(encoded only the "|" character) it returns only the first element of my response.

Weird json nullpointer

I've such a weird error:
Im trying to parse json objects from a url. Which works perfect for example this is the json data:
{"type":"result","rid":"djoezradio",
"data":[{
"title":"Webradio",
"song":"Test",
"track":{
"artist":"Test",
"title":"Test",
"album":"",
"Test":422,
"id":423,
"playlist":{
"id":14,"title":"reggae"
},
"imageurl":"http:\/\/example.com\/static\/example\/covers\/nocover.png"},
"bitrate":"128 Kbps",
"server":"Online","autodj":"Online","source":"Yes","offline":false","listeners":1,
"maxlisteners":500,"reseller":0,"serverstate":true,"sourcestate":true,
"sourceconn":true,"date":"Dec 14, 2013",
"time":"02:13 PM","url":"http:\/\/example.com\/"}]}
This is my code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
JSONObject jObject = new JSONObject(line);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When i do getString("playlist") for example, it just works well, it will return id:14 etc.
The ONLY thing which doesn't work is the object imageurl...
When i want to parse this, it just returns null, while its just there!
Any ideas?
Is there some reason? Its becouse its a .jpeg?
Pleas share, im really stuck.
Try this.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while((line=in.readLine())!=null)
{
builder.append(line);
}
String JSONdata = builder.toString();
Log.i("JsonData",JSONdata);
JSONObject jObject = new JSONObject(JSONdata);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
JSONObject jObject = new JSONObject(JSONdata);
JSONArray jdata = jObject.getJSONArray("data");
JSONObject job = jdata.getJSONObject(0);
JSONObject jObjt = job.getJSONObject("track");
String temp = jObjt.getString("imageurl");
Log.e("rid",temp);

tomcat servlet sessions get merged

I'm developing a server that should receive ,multiple files instantaneously and be able to save them to the local hard drive. After the file received the server should send a response to the client and confirm that the file passed. When i'm trying to send multiple files instantaneously the result is that 1 client received the answer of the second and vice versa.
Does any one have a clue what is the problem with this server?
Here is my servlet code:
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
// get access to file that is uploaded from client
Part p1 = request.getPart("File");
InputStream is = p1.getInputStream();
// read filename which is sent as a part
Part p2 = request.getPart("MetaData");
Scanner s = new Scanner(p2.getInputStream());
String stringJson = s.nextLine(); // read filename from stream
s.close();
json = new JSONObject(stringJson);
fileName = new String(json.getString("FileName").getBytes("UTF-8"));
fileDirectory = BASE + request.getSession().getId();
File dir = new File(fileDirectory);
dir.mkdir();
// get filename to use on the server
String outputfile = BASE + dir.getName() + "/" + fileName; // get path on the server
FileOutputStream os = new FileOutputStream (outputfile);
// write bytes taken from uploaded file to target file
byte[] buffer = new byte[1024];
int ch = is.read(buffer);
final Object lock = new Object();
while (ch != -1) {
synchronized (lock) {
os.write(buffer);
ch = is.read(buffer);
}
}
os.close();
is.close();
}
catch(Exception ex) {
writer.println("Exception -->" + ex.getMessage());
}
finally {
try {
myRequest = request;
try {
printFile(request.getSession().getId(), writer);
} catch (IOException e) {
// TODO Auto-generated catch block
writer.println("Exception -->" + e.getMessage());
}
writer.close();
} catch (InterruptedException e) {
writer.println("Exception -->" + e.getMessage());
}
}
}
Thanks in advance :)

just getting a partial of result from server, httpGet, android,java

I am learning Android now and I am working on how to fire a request and receive a result from server. What I am doing is
// Button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String testURL = "http://djs-corner.appspot.com/getClosestClubs?lat=40.7600624&lon=-73.98558";
// Create http GET method
HttpClient client = new DefaultHttpClient();
// Create http GET method
HttpGet getTest = new HttpGet(testURL);
// Fire a request
try {
HttpResponse response = client.execute(getTest);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);
Log.e("RESULT", result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("ClientProtocolException is ", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("IOException is ", e.toString());
}
}
});
String convertStreamToString(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
return sb.toString();
}
The result I am getting back is just partial of original result.Please look at the image at here. If we take a look at data from the above url, we can see that some of the data are chopped down.
What i am doing wrong at here.

Android: Uploading Strings To Server

I'm trying to let my users be able to report small errors my android application automatically catches to my server. It's nothing big, just a small text box and send button.
It's supposed to send 3 strings (error, optional user description, and time) to a file on my website made specifically to capture those errors. The thing is, I have absolutely no idea how to do so. I only know how to let my application read info from my website but not the other way around.
Do I have to have a special script on my website? Are JSON Strings necessary? I need the string to be saved there. (Not temporarily)
I'm a bit of a newbie so any help is appreciated. Thanks!
- There has to be a script running on your server, eg: php script.
- Its actually a web-service published on the server so that a client can access it.
- Then you will need to do a HTTP Post to the Server, its better to use NameValuePair along with it to send the data.
This is my code for doing HTTP POST:
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = MySSLSocketFactory.getNewHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now", sb + "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*
* catch (ParserConfigurationException e) { // TODO
* Auto-generated catch block e.printStackTrace(); } catch
* (SAXException e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
*/
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method " + sb.toString());
return sb.toString();
}
//////////////////////////// Edited Part ///////////////////////////////////
Server side php code:
<?php
require_once(ROOT.'/lab/lib/xyz_api_int.php');
try {
//setup the sdk
$api = YumzingApiInt::_get(
Config::get('api_int','url'),
Config::get('api_int','key'),
Config::get('api_int','secret')
);
//connect to the api
$api->connect();
//check our token
echo $api->getToken();
} catch(Exception $e){
sysError($e->getMessage());
}
You just need to post values by http to a php script on your server that will save those values in your file or a database.

Categories